canvas旋转图片

最终想要的结果

在这里插入图片描述

思路

1、移动画布中心点

ctx.translate(x,y);//设置画布上的(0,0)位置,也就是旋转的中心点

在这里插入图片描述
2、此时旋转画布,会以(x,y)为中心点
在这里插入图片描述
3、所以我们需要将图片中心点也转移到(x,y)

ctx.drawImage(img,-img.width/2,-img.height/2);//把图片绘制在旋转的中心点,

在这里插入图片描述
4、旋转角度

ctx.rotate(90*Math.PI/180);

在这里插入图片描述

实现

function rotate90(imgUrl, type) {
  return new Promise(function (resolve, reject) {
    try {
      // 1. 创建图片,canvas,获取画布
      var img = new Image(),
          canvas = document.createElement('canvas'),
          ctx = canvas.getContext('2d');
      img.src = imgUrl;
      // 2. 图片加载完成进行图片编辑
      img.onload = function () {
        // 2.1 设置canvas宽高,旋转90° ,宽高互换
        canvas.width = this.height;
        canvas.height = this.width;
        // 2.2 画布中心点(也是起始点)平移至中心(0,0)->(x,y)
        ctx.translate(canvas.width / 2, canvas.height / 2);
        // 2.3 画布旋转90°
        ctx.rotate(270 * Math.PI / 180);
        // 2.4 绘制图像 图像起始点需偏移负宽高
        ctx.drawImage(img, -this.width / 2, -this.height / 2);
        // 2.5返回结果(base64)
        resolve(canvas.toDataURL(type));
      };
    } catch (error) {
      reject(error);
    }
  });
  • 5
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值