javascript - HTML 5 Canvas 。如何仅旋转(保持旋转)一个对象(>1)?

标签 javascript html5-canvas

我正在尝试在 Canvas 中旋转,但尚未找到问题的答案。

一个方格要保持静止。在指定点旋转的另一个方 block 。我可以让整个 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);

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

感谢您的所有帮助。

最佳答案

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

此函数将渲染旋转、缩放和平移的对象,但不会影响任何其他渲染。

顺便说一句,您不需要使用 beginPath 渲染调用以填充或描边开头,例如 ctx.fillRect , ctx.strokeRect , ctx.fillText , ctx.strokeText你只需要使用 ctx.closePath如果您需要从最后一个路径点到前一个 ctx.moveTo 创建一条线ctx.beginPath 之后的点或第一个路径点调用

您也不需要对所有渲染使用保存和恢复。仅当您需要恢复之前的 Canvas 状态时才使用它。

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>

关于javascript - HTML 5 Canvas 。如何仅旋转(保持旋转)一个对象(>1)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41772966/

相关文章:

javascript - 位置重定向到 "sms:123454"在页面加载时不起作用

javascript - 当将相同的坐标指定给 lineTo() 时会发生什么?

javascript - jQuery UI sortable 在排序时触发 css3 动画

javascript - 如何使用 Nodejs 打印 lbl 文件?

javascript - Canvas 锯齿状边缘与线条/笔划的问题

canvas - HTML Canvas,缩放和翻译后的鼠标位置

javascript - HTML5 Tiled Map 将所有图 block 保存为图 block 集中的最后一个图 block

javascript - Fabric.js、Darkroom.js 和 devicePixelRatio 偏移量

javascript - FabricJS - 保存从 JSON 保存/获取 Canvas 的事件

javascript - 关闭状态 Canvas 被删除