图片旋转并保存图片

文章描述了如何使用JavaScript和HTML5CanvasAPI在不同角度(0,90,180,270度)对图片进行旋转,并将旋转后的图片转换为DataURL以便在网页中显示和存储的过程。

let degree = this.rotate;
if (degree === 0) {
this.$message({ message: ‘图片未旋转’, offset: 100 });
return;
}

  const img = new Image();
  // 获取图片src
  img.src = this.currentBigPhoto.img;
  // 获取图片的宽高
  const imgInfo = this.$refs['detail'].getBoundingClientRect();
  if (!imgInfo) {
    return;
  }
  const imgWidth = imgInfo.width;
  const imgHeight = imgInfo.height;
  const canvas = document.createElement('canvas');
  const ctx = canvas.getContext('2d');
  // 获取要旋转的角度
  // 旋转360度 0度
  if (degree === 0) {
    canvas.width = imgWidth;
    canvas.height = imgHeight;
    // ctx.rotate((0 * Math.PI) / 180);
    ctx.drawImage(img, 0, 0, imgWidth, imgHeight);
  } else if (degree === 90) {
    // 旋转90度
    canvas.height = imgHeight;
    canvas.width = imgWidth;
    ctx.rotate((90 * Math.PI) / 180);
    ctx.drawImage(img, 0, -imgWidth, imgHeight, imgWidth);
  } else if (degree === 180) {
    // 旋转180
    canvas.width = imgWidth;
    canvas.height = imgHeight;
    ctx.rotate((180 * Math.PI) / 180);
    ctx.drawImage(img, -imgWidth, -imgHeight, imgWidth, imgHeight);
  } else if (degree === 270) {
    // 旋转270
    canvas.width = imgWidth;
    canvas.height = imgHeight;
    ctx.rotate((270 * Math.PI) / 180);
    ctx.drawImage(img, -imgHeight, 0, imgHeight, imgWidth);
  }
  // 生成图片的url

  const newImg = canvas.toDataURL();
  // this.a = newImg;
  // 重置页面图片的旋转度数
  this.rotate = 0;
  // 新图替换当前图片
  this.currentBigPhoto.img = newImg;
  // 替换存储中的图片
  this.replaceImg(this.currentBigPhoto.id);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值