【问题标题】:How do I rotate pictures inside their circles on an html 5 canvas?如何在 html 5 画布上旋转圆圈内的图片?
【发布时间】:2018-12-16 19:55:21
【问题描述】:

我正在尝试使徽标在其圈内旋转(如果可能,以随机速度),但我无法实现。

我试过这个:

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

【问题讨论】:

    标签: javascript html canvas rotation


    【解决方案1】:

    关键是先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

    【讨论】:

    • 超级明星!正是我想要的,+1000 :-)
    • 太棒了!如果这解决了您的问题,请考虑接受作为答案:)
    • 啊,是的!完成队友:-)
    【解决方案2】:

    最好在函数/迭代开始时保存(),在函数/迭代结束时使用restore()。

    我建议写一个函数来绘制对象:

    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])
    

    或者不写函数,只在迭代开始时save(),结束时restore()。

    另一个工作示例: https://codepen.io/anon/pen/RBbRJr?editors=0010

    【讨论】:

      猜你喜欢
      • 2013-09-06
      • 1970-01-01
      • 2015-10-22
      • 1970-01-01
      • 1970-01-01
      • 2019-03-03
      • 1970-01-01
      • 1970-01-01
      • 2011-02-10
      相关资源
      最近更新 更多