首页 > 解决方案 > 如何在 html 5 画布上旋转圆圈内的图片?

问题描述

我试图让徽标在他们的圈子内旋转(如果可能的话以随机速度),但我无法做到这一点。

我试过这个:

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();

但正如你所看到的,这些标志并不是在它们自己的中心旋转。

笔:https ://codepen.io/Le-future/pen/gKNoEE

标签: javascripthtmlcanvasrotation

解决方案


关键是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();
    }

工作叉https://codepen.io/anon/pen/bjbeoq


推荐阅读