如何旋转我用javascript制作的正方形的函数?
如何将此函数旋转45度,使其成为菱形。我正在制作一个游戏,其中这个函数是玩家,你可以用箭头键移动它,但我希望它是钻石形状,而不是正方形如何旋转我用javascript制作的正方形的函数?,javascript,rotation,Javascript,Rotation,如何将此函数旋转45度,使其成为菱形。我正在制作一个游戏,其中这个函数是玩家,你可以用箭头键移动它,但我希望它是钻石形状,而不是正方形 function morty() { ctx.fillStyle = "rgb(255,255,255)"; ctx.fillRect(0,0,cv.width,cv.height); ctx.fillStyle = "rgb(255,255,255)"; ctx.fillRect(x1,y1,50,50); ctx.
function morty() {
ctx.fillStyle = "rgb(255,255,255)";
ctx.fillRect(0,0,cv.width,cv.height);
ctx.fillStyle = "rgb(255,255,255)";
ctx.fillRect(x1,y1,50,50);
ctx.fillStyle = "rgb(175,80,247)";
ctx.fillRect(x1,y1,45,45);
ctx.fillStyle = "rgb(50,100,150)";
ctx.fillRect(x1,y1,40,40);
ctx.fillStyle = "rgb(0,255,255)";
ctx.fillRect(x1,y1,32,32);
ctx.fillStyle = "rgb(250,0,250)";
ctx.fillRect(x1,y1,27,27);
ctx.fillStyle = "rgb(47,47,47)";
ctx.fillRect(x1,y1,20,20);
ctx.fillStyle = "rgb(255,255,0)";
ctx.fillRect(x1,y1,10,10);
ctx.fillStyle = "rgb(0,200,180)";
ctx.fillRect(x1,y1,5,5);
}
你的正方形飞行对角线是因为当你在旋转后移动
(1,0)
时,你实际上是在画布上移动(0.707,0.707)
,因为坐标系旋转ctx.rotate
因此,您希望使(1,0)
translate real在画布上具有移动(1,0)
的效果,画布不应旋转,然后最好将x1
和y1
移出。逻辑是
(0,0)
上画一些正方形(因为ctx.rotate
位于(0)的中心
0)
)(x1,y1)
ctx.save
保存当前未更改的坐标,以便以后我们可以返回到它x1,y1
不受旋转的影响,所以我们首先调用ctx.translate(x1,y1)代码>,它将在画布上移动任何旋转(x1,y1)
ctx.rotate(45/180*Math.PI)代码>使以下绘图操作旋转45度
x1,y1上,而是画在(0,0)
的中心
ctx.restore
,因此如果您有其他东西要绘制,它仍将绘制在法线坐标上,而不是旋转移动的坐标上var cv=document.getElementById('test');
var ctx=cv.getContext('2d');
var x1=cv.width>>1;
变量y1=cv高度>>1;
函数morty(){
//透明帆布
ctx.fillStyle=“rgb(255255)”;
ctx.fillRect(0,0,cv.宽度,cv.高度);
ctx.save();
//这使得下面的任何内容都具有x1,y1平移/
ctx.translate(x1,y1);
//这将在(0,0)处旋转任何低于45度的操作
ctx旋转(45/180*Math.PI);
ctx.fillStyle=“rgb(255255)”;
ctx.fillRect(-25,-25,50,50);
ctx.fillStyle=“rgb(175,80247)”;
ctx.fillRect(-22.5,-22.5,45,45);
ctx.fillStyle=“rgb(50100150)”;
ctx.fillRect(-20,-20,40,40);
ctx.fillStyle=“rgb(0255255)”;
ctx.fillRect(-16,-16,32,32);
ctx.fillStyle=“rgb(250,0250)”;
ctx.fillRect(-13.5,-13.5,27,27);
ctx.fillStyle=“rgb(47,47,47)”;
ctx.fillRect(-10,-10,20,20);
ctx.fillStyle=“rgb(255255,0)”;
ctx.fillRect(-5,-5,10,10);
ctx.fillStyle=“rgb(0200180)”;
ctx.fillRect(-2.5,-2.5,5,5);
//这使得操作后仍有正常的cordinate系统。
ctx.restore();
}
//测试使用情况。
document.body.addEventListener('keydown',函数(e){
console.log(例如keyCode);
开关(如钥匙代码){
案例37:
x1-=10;
打破
案例38:
y1-=10;
打破
案例39:
x1+=10;
打破
案例40:
y1+=10;
打破
违约:
回来
}
莫蒂();
})
莫蒂()代码>
您可以使用旋转功能ctx.rotate(45*Math.PI/180)代码>。请记住,在ctx.fillRect之前添加它。可以旋转上下文中绘制的内容,而不是旋转函数对不起,我是一个主要的初学者。你的权利,我想旋转在上下文中画的东西。@craigo当我这样做的时候,我的正方形一直沿着对角线一次又一次地飞行