HTML 5 Canvas。如何旋转(保持旋转)只有一个对象(> 1)?

时间:2017-01-20 21:54:58

标签: javascript html5-canvas

我正试图在画布上旋转,我没有找到问题的答案。

一个方格是保持不动。另一个在指定点旋转的方块。我可以让整个画布在那一点旋转,或者根本不旋转。但我不能让一个方格静止而一个方格旋转。

请在此处查看我的codepen演示:http://codepen.io/richardk70/pen/EZWMXx

javascript:

HEIGHT = 400;
WIDTH = 400;

function draw(){

var ctx = document.getElementById("canvas").getContext('2d');
ctx.clearRect(0,0,WIDTH,HEIGHT);

// draw black square
ctx.save();
ctx.fillStyle = "black";
ctx.beginPath();  
ctx.fillRect(75,75,100,100);
ctx.closePath();
ctx.restore();

// attempt to rotate small, maroon square only
ctx.save();
ctx.translate(225,225);

// small maroon square
ctx.fillStyle = "maroon";
ctx.beginPath();
ctx.fillRect(-25,-25,50,50);
ctx.closePath();
ctx.rotate(.1);
ctx.translate(-225,-225);

// comment out below line to spin
// ctx.restore();

window.requestAnimationFrame(draw);
}

window.requestAnimationFrame(draw);

我知道我可以做分层画布,但肯定可以在一个画布层中完成吗?本教程(https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API/Tutorial/Basic_animations)中的时钟不是正确的吗?

感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

要仅旋转一个图像或渲染,您需要将画布变换状态恢复为默认值。

此功能将使您的对象旋转缩放和平移,但不会影响任何其他渲染。

BTW你不需要使用beginPath是渲染调用以填充或描边开始,例如ctx.fillRectctx.strokeRectctx.fillTextctx.strokeText,你只需要如果您需要在ctx.closePath调用

之后创建从最后一个路径点到上一个ctx.moveTo点或第一个路径点的行,请使用ctx.beginPath

您也不需要对所有渲染使用保存和恢复。只有在需要恢复上一个画布状态时才使用它。

ctx = canvas.getContext("2d");

function drawBox(col,size,x,y,scale,rot){
    ctx.fillStyle = col;
    // use setTransform as it overwrites the canvas transform rather than multiply it as the other transform functions do
    ctx.setTransform(scale, 0, 0, scale, x, y);
    ctx.rotate(rot);
    ctx.fillRect(-size / 2,-size / 2, size, size);  
}


function update(time){
    ctx.clearRect(0,0,512,256)
    drawBox("black",100,125,125,1,0); // draw none rotated box
    drawBox("maroon",50,225,125,1,time / 500); // draw rotating box
    drawBox("green",25,275,100,1,-time / 250); // draw rotating box
    drawBox("green",25,275,150,1,-time / 250); // draw rotating box
    // after using transforms you need to reset the transform to the default
    // if you plan to render anything in the default coordinate system
    ctx.setTransform(1, 0 ,0 , 1, 0, 0); // reset to default transform

    requestAnimationFrame(update);
}

requestAnimationFrame(update);
<canvas id="canvas" width="512" height="256"></canvas>