简体   繁体   English

在画布中为旋转的图像设置动画

[英]animating a rotated image in canvas

hey guys i have a function that strokes a line based on the angle received from the user and also moves an image using some basic maths. 大家好,我有一个功能,可以根据从用户那里收到的角度画一条线,并且还可以使用一些基本数学来移动图像。 the only problem is i am unable to rotate image based on that angle as if i put this inside animation frame loop it doesn't work .please help 唯一的问题是我无法基于该角度旋转图像,就像我将其放在动画帧循环中一样。不起作用。请帮助

function move() 
{

var theCanvas=document.getElementById("canvas1");
var context=theCanvas.getContext("2d");
context.clearRect(0, 0, theCanvas.width,  theCanvas.height );
// context.fillStyle = "#EEEEEE";
 //context.fillRect(0, 0,theCanvas.width,  theCanvas.height );

       context.beginPath();
       context.setLineDash([3,2]);
       context.lineWidth=10;
       context.strokeStyle="black";
       context.moveTo(x1,y1);
       context.lineTo(x2,y2);
       context.stroke();

    context.drawImage(srcImg,x1+x_fact,y1-100+y_fact);
    x_fact=x_fact+0.5;      
    y_fact=m*x_fact+c;
    requestAnimationFrame(move);
}
move(); 

now please suggest me a way to rotate the image on the angle input only once so it can face according to the path and move in it. 现在,请为我建议一种仅在角度输入上旋转图像一次的方法,以便它可以根据路径面对并在其中移动。

thank you in advance. 先感谢您。

If you want to rotate the image by its corner use something like this: 如果要旋转图像的角,请使用以下方法:

... your other code here ...

var x = x1+x_fact,                 // for simplicity
    y = y1-100+y_fact;

context.save();                    // save state
context.translate(x, y);           // translate to origin of rotation
context.rotate(angle);             // rotate, provide angle in radians

context.drawImage(srcImg, 0, 0);   // as we are translated we draw at [0,0]
context.restore();                 // restore state removing transforms

If you want to rotate it by center simply translate, rotate and then translate back 50% of the image's width and height. 如果要通过中心旋转,只需平移,旋转,然后向后平移图像宽度和高度的50%。

save/restore are relative expensive operations - you can simply reset transformation all together after each draw if you don't need transformations elsewhere: 保存/恢复是相对昂贵的操作-如果您不需要其他地方的转换,则可以在每次绘制后简单地将转换全部重置在一起:

context.setTransform(1, 0, 0, 1, 0, 0); // instead of restore(), remove save()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM