JS操作图片旋转角度并生成新图片


<!DOCTYPE html>

<html lang="en">

<head>

  <meta charset="UTF-8">

  <meta http-equiv="X-UA-Compatible" content="IE=edge">

  <meta name="viewport" content="width=device-width, initial-scale=1.0">

  <title>Document</title>

  <script src="./rotate.js"></script>

</head>

<body>



  <script>

    /*

      旋转图片角度并重新生成图片

      @author:zijian_chen

      params:{

        ele:目标Dom元素(可不传)

        src:图片路径,

        angle:旋转角度 取值范围(0-3) 0°/90°/180°/270°;

      }

      .rotate() // 调用旋转方法 返回promise对象

      .then(img => {}) // 自由操作

    */

      const e = new imgRotate({

        src:'.././wenjian/asd.jpg',

        angle:2

      })

      .rotate()

      .then(item => {

        console.log(item);

        document.body.appendChild(item)

      })

  </script>



</body>

</html>
class imgRotate {
  constructor({ ele, src, angle }) {
    this.ele = ele;
    this.image = new Image();
    this.image.src = src;
    this.canvas = document.createElement("canvas");
    this.ctx = this.canvas.getContext("2d")
    this.angle = angle;
  }

  async rotate () {
    let img = new Image(),
      angles = [0, 90, 180, 270];
    this.image.onload = _ => {
      if (angles[this.angle] % 180 === 0) {
        this.canvas.width = this.image.width;
        this.canvas.height = this.image.height;
      } else {
        this.canvas.width = this.image.height;
        this.canvas.height = this.image.width;
      }
      switch (this.angle) {
        case 0: // 0
          this.ctx.translate(0, 0)
          break;
        case 1: // 90
          this.ctx.translate(this.canvas.width, 0)
          break;
        case 2:// 180
          this.ctx.translate(this.canvas.width, this.canvas.height)
          break;
        case 3: // 270
          this.ctx.translate(0, this.canvas.height)
          break;
        default:
          throw new ReferenceError("No angle");
          break;
      }
      this.ctx.rotate(angles[this.angle] * Math.PI / 180);
      this.ctx.drawImage(this.image, 0, 0, this.image.width, this.image.height, 0, 0, this.image.width, this.image.height);

      img.src = this.canvas.toDataURL("image/png");
      if (this.isDom()) this.ele.appendChild(img);
    }
    return img;
  }

  isDom () {
    return typeof this.ele === 'object' && this.ele.nodeType === 1 && typeof this.ele.nodeName === 'string';
  }
}

// export default imgRotate

暂时只做了这四个常用角度的,不符合需求的,支持自己二开喔~

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值