【发布时间】:2017-01-20 21:54:58
【问题描述】:
我正在尝试在画布中旋转,但我还没有找到我的问题的答案。
一个正方形要保持静止。在指定点旋转的另一个正方形。我可以让整个画布在那时旋转,或者根本不旋转。但是我不能让一个正方形是静态的,而一个是旋转的。
请在此处查看我的 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) 不正是这样做的吗?
感谢您的任何帮助。
【问题讨论】:
-
如果您查看链接的示例,它会根据当前时间调整旋转量,因此每次绘制调用都会稍微移动行星。您正在尝试在上下文中累积旋转,但这不是它的工作方式。