图像和画布旋转

时间:2016-11-18 15:33:34

标签: javascript html5-canvas

我尝试旋转图像并使用箭头键在画布上移动它。计划是让左右键控制图像的旋转,上下键控制运动,有点像坦克!

我可以成功地围绕中心点旋转图像并将其放回到应该在画布中的位置但是一旦我旋转它说45度,我希望向上键向右移动,旋转180度和向上键移动它可以在画布上等。我可以使用左/右键旋转图像,但上/下键总是在画布上/下。

我不知何故需要将画布坐标旋转与图像相同的量?

这是我到目前为止所做的并且是我的绘画功能..

ctx.save();
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.translate(T1.x + base_image.width/2, T1.y + base_image.height/2);

ctx.rotate(rotation * Math.PI / 180);

ctx.translate(-(T1.x+ base_image.width/2), -(T1.y+ base_image.height/2));
ctx.drawImage(base_image,T1.x,T1.y);

ctx.stroke();
ctx.restore()

T1.x和T1.y是图像的x和y坐标。

由于

2 个答案:

答案 0 :(得分:3)

终于搞定了......

解决方案是将旋转和移动分开,而不是尝试使用ctx.translate完成所有操作。

在每100Hz调用的绘图函数中

ctx.save();
ctx.translate(T1.x + base_image.width/2, T1.y + base_image.height/2);
ctx.rotate( rotation*Math.PI/180 );
ctx.drawImage( base_image, -base_image.width/2, -base_image.height/2 );
ctx.restore();
ctx.stroke();

左键例如:

rotation=rotation-5;
Draw();

up键例如:

var radians = (rotation*Math.PI / 180)
T1.x += 4 * Math.cos(radians);
T1.y += 4 * Math.sin(radians);
Draw();

注意:为此,我必须将油漆中图像的默认方向更改为45度。

答案 1 :(得分:1)

在Firefox,Chrome和Edge上绘制旋转,统一缩放图像的最快方法

// when the image has loaded add the center offsets
image.onload = function(){
   // ... your code 
   this.centerX = -this.width/2;
   this.centerY = -this.height/2;
}

// When rendering
// x,y position of image center
// scale the uniform scale
// rotate angle in radians starting at 0 and + clockwise
var xdx = Math.cos(rotate) * scale;
var xdy = Math.sin(rotate) * scale;
ctx.setTransform(xdx, xdy, -xdy, xdx, x, y);
ctx.drawImage(image,image.centerX,image.centerY)

使用额外的sin和cos以及两次乘法的上述方法在Chrome上显着更快,在FF上稍快一些,我忘记了Edge上的边距但是它比下一个最快的方法更快

ctx.setTransform(scale, 0, 0, scale, x, y);
ctx.rotate(rotate);
ctx.drawImage(image,image.centerX,image.centerY);

虽然我正在离开画布变换状态。您可以继续使用这两种方法,而无需重置画布状态。完成所有渲染后,使用

恢复当前变换
ctx.setTransform(1,0,0,1,0,0);     

要在每次从度数转换为弧度时节省一点时间,请创建一个const const DEG2RAD = Math.PI/180;,然后您可以使用var radians = degrees * DEG2RAD;转换或保存输入const D2R = Math.PI/180;或将其称为{{ 1}}