JavaScript画布:连续旋转画布绘制的图像

JavaScript画布:连续旋转画布绘制的图像,javascript,animation,canvas,html5-canvas,image-rotation,Javascript,Animation,Canvas,Html5 Canvas,Image Rotation,我试图在保持相同位置的同时旋转一个精灵 如何持续旋转画布上绘制的图像 例如,我的假设是使用setInterval每隔300ms调用一个函数,但我不知道如何连续旋转画布上的单个元素 欢迎提出任何建议。动画和旋转图像 动画 要使用画布设置任何内容的动画,首先需要设置动画循环。通常使用一个动画循环来渲染所有画布内容 动画的计时由使用(RAF)创建的时间事件控制,这会在1/60秒内自动调用下一帧(如果可能)。您需要在动画循环中的某个点调用RAF function mainLoop(time) { //

我试图在保持相同位置的同时旋转一个精灵

如何持续旋转画布上绘制的图像

例如,我的假设是使用setInterval每隔300ms调用一个函数,但我不知道如何连续旋转画布上的单个元素

欢迎提出任何建议。

动画和旋转图像 动画 要使用画布设置任何内容的动画,首先需要设置动画循环。通常使用一个动画循环来渲染所有画布内容

动画的计时由使用(RAF)创建的时间事件控制,这会在1/60秒内自动调用下一帧(如果可能)。您需要在动画循环中的某个点调用RAF

 function mainLoop(time) { // time is automatically passed to the function
      ctx.clearRect(0, 0, canvas.width, canvas.height); // clear canvas

      // draw what you need for the animation

      requestAnimationFrame(mainLoop); // set up the next frame
 }

 // to start the animation call RAF 
 requestAnimationFrame(mainLoop); // set up the next frame
动画循环的示例

 function mainLoop(time) { // time is automatically passed to the function
      ctx.clearRect(0, 0, canvas.width, canvas.height); // clear canvas

      // draw what you need for the animation

      requestAnimationFrame(mainLoop); // set up the next frame
 }

 // to start the animation call RAF 
 requestAnimationFrame(mainLoop); // set up the next frame
旋转图像。 可以使用2D上下文函数和围绕图像中心旋转图像

setTransform
覆盖现有的转换,因此您不必担心画布状态

若要围绕图像中心旋转,需要绘制偏移其高度一半的图像,否则图像将围绕左上角旋转

旋转图像的示例函数

 function drawImageRotated(img, x, y, rot){
      ctx.setTransform(1, 0, 0, 1, x, y); // set the scale and the center pos
      ctx.rotate(rot); // set the rotation
      ctx.drawImage(img, -img.width /2, -img.height /2); // draw image offset 
                                                         // by half its width
                                                         // and heigth
      ctx.setTransform(1, 0, 0, 1, 0, 0); // restore default transform
}
把它们放在一起 下一个示例加载图像,设置画布,并使用主循环旋转图像。注意:我在图像绘制功能中添加了比例,因为加载的图像不适合

const img=new Image();
img.src=”https://i.stack.imgur.com/C7qq2.png?s=328&g=1";
img.onload=()=>{requestAnimationFrame(mainLoop)}//加载时启动
const ctx=canvas.getContext(“2d”);
函数drawImageRotated(img、x、y、scale、rot){
设置变换(比例,0,0,比例,x,y);
旋转(旋转);
ctx.图纸图像(img,-img.width/2,-img.height/2);
setTransform(1,0,0,1,0,0);
}
函数主循环(时间){
clearRect(0,0,canvas.width,canvas.height);
drawImageRotated(img,canvas.width/2,canvas.height/2,0.5,time/500);
requestAnimationFrame(主循环);
}

我不知道这个教程是否好,这是我在谷歌上发现的第一个:这个教程允许通过
上下文进行单元素旋转。保存
上下文。恢复
,但是我仍然无法继续旋转。非常有用且信息丰富的答案,谢谢你的帮助!