gpt4 book ai didi

javascript - 在 Canvas 中围绕其中心旋转图像

转载 作者:可可西里 更新时间:2023-11-01 02:03:38 26 4
gpt4 key购买 nike

我正在尝试在 Canvas 上制作我的第一个图像动画。我希望图像旋转,但我的代码中有些地方不正确。有任何想法吗?这一切都在准备好的 jquery 文档中:

var canvas = document.getElementById('logobg1');  
var ctx = canvas.getContext('2d');

var img = new Image(); // Create new Image object
img.src = 'images/containerbg.png'; // Set source path // set img src

img.onload = function(){ // when image loads
ctx.drawImage(img,0,0);
setInterval(function() {
ctx.save();
ctx.clearRect(-ctx.canvas.width/2, -ctx.canvas.height/2, ctx.canvas.width, ctx.canvas.height);
ctx.drawImage(img,0,0);
ctx.translate(ctx.canvas.width/2, ctx.canvas.height/2); // set canvas context to center
ctx.rotate(Math.PI / 180 * 0.5); // 1/2 a degree
ctx.restore();
}, 16);
}

最佳答案

只需更改代码的顺序,即

ctx.rotate(...);

ctx.drawImage(...);

查看工作示例 http://jsbin.com/owuyiq/

$(function () {
var canvas = document.getElementById('logobg1');
var ctx = canvas.getContext('2d');
var img = new Image();

var ang = 0; //angle
var fps = 1000 / 25; //number of frames per sec
img.onload = function () { //on image load do the following stuff
canvas.width = this.width << 1; //double the canvas width
canvas.height = this.height << 1; //double the canvas height
var cache = this; //cache the local copy of image element for future reference
setInterval(function () {
ctx.save(); //saves the state of canvas
ctx.clearRect(0, 0, canvas.width, canvas.height); //clear the canvas
ctx.translate(cache.width, cache.height); //let's translate
ctx.rotate(Math.PI / 180 * (ang += 5)); //increment the angle and rotate the image
ctx.drawImage(img, -cache.width / 2, -cache.height / 2, cache.width, cache.height); //draw the image ;)
ctx.restore(); //restore the state of canvas
}, fps);
};

img.src = 'http://i.stack.imgur.com/Z97wf.jpg?s=128'; //img
});

关于javascript - 在 Canvas 中围绕其中心旋转图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4422293/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com