在画布中动画旋转的图像

时间:2014-03-28 09:37:19

标签: javascript html5 canvas

嘿伙计们,我有一个功能,根据用户收到的角度划线,并使用一些基本数学移动图像。唯一的问题是我无法根据该角度旋转图像,好像我把它放在动画帧循环中它不起作用。请帮助

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(); 

现在请建议我一种方法只在角度输入上旋转图像一次,这样它就可以根据路径面对并移动到其中。

提前谢谢。

1 个答案:

答案 0 :(得分:0)

如果您想通过角落旋转图像,请使用以下内容:

... 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

如果您想按中心旋转,只需翻译,旋转然后平移50%的图像宽度和高度。

保存/恢复是相对昂贵的操作 - 如果您不需要在其他地方进行转换,您可以在每次绘制后简单地重置转换:

context.setTransform(1, 0, 0, 1, 0, 0); // instead of restore(), remove save()
相关问题