在画布中围绕图像中心旋转图像
我正在尝试在画布上制作我的第一个图像动画。我希望图像旋转,但我的代码中有些东西不正确。有什么想法吗?这一切都在 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);
}
I'm trying to do my first image animation on canvas. I want the image to rotate but something is not correct in my code. Any ideas? This is all in a jquery document ready:
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);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
只需更改代码的顺序,即
查看工作示例http://jsbin.com/owuyiq/< /a>
just change the order of your code, i.e.,
See a working example http://jsbin.com/owuyiq/
基于上面的评论,但更简单,更普通。这对我来说非常有效。
当然,您应该使用clearRect来擦除每次渲染时的画布。
Based on the comments above, but a bit more simple and in vanilla. This one worked for me perfectly.
Of course you should use clearRect in order to erase the canvas on each rendering.
根据已接受的答案,此示例允许您使用固定的画布大小(与图像大小无关):
工作示例: jsbin.com/suwovibove/
注意:尝试删除
ctx.save
和ctx.restore
带来酷炫的旋转。Based in the accepted answer, this example, allows you to use a fixed canvas size (and not in relation to the image size):
Working example: jsbin.com/suwovibove/
Note: try removing
ctx.save
andctx.restore
for a cool spin.