我试图使徽标在其圈子内旋转(如果可能,以随机速度旋转),但我无法实现。
我尝试过:
ctx.save();
ctx.rotate(0.10);
ctx.drawImage(object.image, object.x-object.size/2, object.y-object.size/2, object.size, object.size);
ctx.restore();
但是正如您所看到的,徽标不是在自己的中心旋转。
答案 0 :(得分:2)
关键是首先translate
,然后rotate
在spawnRandomObject
// add the new object to the objects[] array
object.rot = 0;
objects.push(object);
在animate
for (var i = 0; i < objects.length; i++) {
var object = objects[i];
object.y += object.speed*0.1;
object.rot += 0.05; // rotation speed
ctx.globalAlpha = object.opacite;
ctx.beginPath();
ctx.arc(object.x, object.y, object.size/1.25, 0,2*Math.PI);
ctx.fillStyle = object.couleur;
ctx.fill();
ctx.restore();
ctx.save();
ctx.translate(object.x, object.y);
ctx.rotate(object.rot);
ctx.drawImage(object.image, -object.size/2, -object.size/2, object.size, object.size);
ctx.restore();
}
答案 1 :(得分:0)
最佳做法是在函数/迭代的开始处保存(),在函数/迭代的结束处恢复()。
我建议编写一个绘制对象的函数:
function drawObject(object)
{
ctx.save()
object.y += object.speed;
ctx.translate(object.x - object.size / 2, object.y - object.size / 2);
object.angle += 0.01; // can be randomized
ctx.rotate(object.angle);
ctx.globalAlpha = object.opacite;
ctx.beginPath();
ctx.arc(0, 0, object.size/1.25, 0,2*Math.PI);
ctx.fillStyle = object.couleur;
ctx.fill();
ctx.drawImage(object.image, -object.size/2, -object.size/2, object.size, object.size);
ctx.restore();
}
您可以在循环中调用它为:
for (var i = 0; i < objects.length; i++) {
drawObject(objects[i])
或者不编写函数,只需在迭代开始时保存()并在结束时恢复(
)。