【问题标题】:rotate and move picture at the same moment canvas旋转和移动图片同时画布
【发布时间】:2015-03-17 20:49:14
【问题描述】:

我想旋转和移动图像,但是当我使用 .rotate() 时,我使用坐标系旋转 canvas.context。当我尝试更改 x 坐标时,我无法水平移动对象 - 它们在新的(对角线)x 轴上移动:( jsfiddle code 如何水平移动它?

        ctx.clearRect(0, 0, canvas.width, canvas.height);
        ctx.save();
        ctx.translate(100, 100);
        ctx.rotate(r1/180)
        ctx.translate(-100, -100);
        ctx.drawImage(image, x1, x2, 100, 100);
        ctx.rotate(-r1/180);
        ctx.restore();
         x1 += 1;
         r1 += 1;

【问题讨论】:

    标签: javascript html canvas html5-canvas


    【解决方案1】:

    使用变换同时移动和旋转图像如下:

    • 清除画布。

    • 转换到您希望图像中心点所在的新坐标。翻译实际上是重新定位画布的 [0,0] 原点。在画布上绘制的所有像素都将在新原点绘制,任何旋转都会导致所有像素围绕新原点旋转。

    • 按所需的弧度旋转。

    • 通过负半宽度和负半高度绘制图像偏移量。这是将图像的中心点直接定位在原点(原点 == 旋转点)上所必需的。

    示例代码和演示:

    var canvas=document.getElementById("canvas");
    var ctx=canvas.getContext("2d");
    var cw=canvas.width;
    var ch=canvas.height;
    
    var centerX=50;
    var centerY=200;
    var radianAngle=0;
    
    var img=new Image();
    img.src="https://i.stack.imgur.com/K2Npl.png";
    img.onload=start;
    
    function start(){
      requestAnimationFrame(animate);
    }
    
    function animate(time){
      // request another animation frame
      if(centerX<cw){
        requestAnimationFrame(animate);
      }
    
      // clear the canvas
      ctx.clearRect(0,0,cw,ch);
    
      // draw the sky
      ctx.fillStyle='skyblue';
      ctx.fillRect(0,0,cw,ch);
      
      // translate to the new point where
      // you want the images center to be
      ctx.translate(centerX,centerY);
    
      // rotate the canvas
      ctx.rotate(radianAngle);
    
      // draw the image
      // offset by half-width & half-height
      // because img.center == centerX,centerY
      ctx.drawImage(img,-img.width/2,-img.height/2);
    
      // undo the transforms
      ctx.setTransform(1,0,0,1,0,0);
    
      // draw grass
      ctx.fillStyle='forestgreen';
      ctx.fillRect(0,200,cw,ch-200);
    
      // draw soil
      ctx.fillStyle='saddlebrown';
      ctx.fillRect(0,200,cw,5);
    
      // move 
      centerX+=.2;
      centerY+=(centerX<cw/2)?-.2:.2;
    
      // rotate
      radianAngle+=Math.PI/60;
    }
    body{background-color:ivory; padding:10px;}
    #canvas{border:1px solid red;}
    &lt;canvas id="canvas" width=500 height=170&gt;&lt;/canvas&gt;

    【讨论】:

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