Fork me on Bolg '◡'

canvas处理切图并旋转图片

场景描述

需要把大图中的框的图片给显示出来~类似下图

如果将图片倒置,则显示对应倒置的图片~类似下图

代码实现

let base64Canvas = document.createElement('canvas');
let base64Context = this.base64Canvas.getContext('2d');
// 获取框的坐标和宽高
let {  w, h, x, y } = data;
base64Canvas.width = w;
base64Canvas.height = h;
base64Context.drawImage(img, x, y, w, h, 0, 0, w, h);
let base64Img = base64Canvas.toDataURL("image/png");
console.log(base64Img)

因为框本身就是在图片上切的,所以直接使用canvas的drawImage方法即可。

图片旋转

由于框是基于SVG画的,当图片旋转后,框的坐标其实还是基于正框下的位置,这里我想了好几种方法,最后觉得还是在基于正框切图下的基础上,再进行旋转最方便。也就是先执行上面的正常切图,再旋转~

 rotateDegCutImg(w, h, rotateDeg, base64Img, callbackHandler) {
    let canvas66 = document.createElement('canvas');
    let ctx66 = canvas66.getContext('2d');
    let img66 = new Image();
    img66.setAttribute('crossOrigin', 'anonymous');
    img66.src = base64Img;
    canvas66.width = w;
    canvas66.height = h;

    img66.onload = () => {
      if (rotateDeg == 90) { // 90
        // 宽高互换
        canvas66.width = h;
        canvas66.height = w;
        ctx66.rotate(Math.PI / 2)
        ctx66.drawImage(img66, 0, -h, w, h)
      }
      if (rotateDeg == 180) {
        ctx66.rotate(Math.PI)
        ctx66.drawImage(img66, -w, -h, w, h)
      }
      if (rotateDeg == 270) { // 270
        // 宽高呼唤
        canvas66.width = h;
        canvas66.height = w;
        ctx66.rotate(Math.PI / 2 * 3)
        ctx66.drawImage(img66, -w, 0, w, h)
      }

      let img66Src = canvas66.toDataURL("image/png");

      if (callbackHandler) {
        callbackHandler(img66, img66Src)
      }
    }
  }
posted @ 2022-12-13 19:06  webhmy  阅读(512)  评论(0编辑  收藏  举报