在同一时刻画布旋转和移动图片

时间:2015-01-19 18:48:35

标签: javascript html5 canvas html5-canvas

我想旋转并移动图像,但是当我使用.rotate()时,我使用坐标系旋转canvas.context。当我尝试更改x-coord时,我无法水平移动对象 - 它们在新的(对角线)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;

1 个答案:

答案 0 :(得分:0)

使用变换同时移动&旋转图像是这样的:

  • 清除画布。

  • 转换为您希望图像的CENTERpoint所在的新坐标。翻译实际上重新定位画布的[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;
}
&#13;
body{background-color:ivory; padding:10px;}
#canvas{border:1px solid red;}
&#13;
<canvas id="canvas" width=500 height=170></canvas>
&#13;
&#13;
&#13;

相关问题