canvas内image旋转

目前理解下来就是旋转的不是image本身,而是要drawImage的那个canvas的2d context,context本身的绘制就是把图片本来的样子draw出来,至于旋转,透明度之类的效果都是对context在操作。

至于做到让image绕自身中心店改变角度的做法,就是让context坐标转换,并且让context改变角度,context.rotate()方法接受根据角度转换之后的弧度。

 

设置一个坐标,让image坐上角定位在此坐标并以此坐标为锚点选转

  context.translate(buildingImgX,buildingImgY);
        context.rotate(50 * Math.PI / 180);
        context.translate(-buildingImgX,-buildingImgY);
        context.drawImage(buildingImg,buildingImgX ,buildingImgY );

 

设置一个坐标,让image中心店点定位在此坐标并以此坐标为锚点选转

  buildingImgX = canvasWidth - buildingImg.width/2 - 100;
        buildingImgY = canvasHeight / 2;

        context.translate(buildingImgX,buildingImgY);
        context.rotate(10 * Math.PI / 180);
        context.translate(-buildingImgX,-buildingImgY);
        context.drawImage(buildingImg,buildingImgX - buildingImg.width/2,buildingImgY - buildingImg.height/2);

 

 

 

 

 

转帖别人代码:

 var canvas = document.getElementById('c1');
    var ctx1 = canvas.getContext('2d');
    var image1 = new Image();
    image1.onload = function() {
      // regular rotation about center
      var xpos = canvas.width/2;
      var ypos = canvas.height/2;
      ctx1.drawImage(image1, xpos - image1.width / 2, ypos - image1.height / 2);
      ctx1.save();
      ctx1.translate(xpos, ypos);
      ctx1.rotate(47 * Math.PI / 180);//旋转47度
      ctx1.translate(-xpos, -ypos);
      ctx1.drawImage(image1, xpos - image1.width / 2, ypos - image1.height / 2);
      ctx1.restore();
    }
    image1.src = 'image.png';

 

你可能感兴趣的:(canvas内image旋转)