Pure style or use JS canvas to achieve image rotation

The effect is as shown in the figure:

image-20230131142927615

Click to rotate, and the picture will rotate accordingly. There are 4 directions in total, which are 0, 90, 180, and 270 degrees.

1. Implementation of CSS3

If it is according to my thinking, it is naturally the attribute CSS3used .transformrotate

img{
    
    
    transform:rotate(90deg);
}

The actual situation can also be rotated, which is simple and convenient, and is only suitable for temporary viewing.

Two, JS canvas implementation

The principle is roughly to convert the img image into a canvas object, output a new image path, and echo it to the img tag.

The general code is as follows:

/** 图片旋转后返回base64
 * @param {Object} img 图片对象
 * @param {Number} rotate 旋转角度 90° 180° 270° 360°=default
 * @returns {String} base64图片
 *
 */
export function imageRotate(img, rotate) {
    
    
  let canvas = document.createElement("canvas");
  let ctx = canvas.getContext("2d");
  switch (rotate) {
    
    
    case 90: // 旋转90°
      canvas.width = img.height;
      canvas.height = img.width;
      ctx.rotate((90 * Math.PI) / 180);
      ctx.drawImage(img, 0, -img.height, img.width, img.height);
      break;
    case 180: // 旋转180°
      canvas.width = img.width;
      canvas.height = img.height;
      ctx.rotate((180 * Math.PI) / 180);
      ctx.drawImage(img, -img.width, -img.height, img.width, img.height);
      break;
    case 270: // 旋转270°
      canvas.width = img.height;
      canvas.height = img.width;
      ctx.rotate((-90 * Math.PI) / 180);
      ctx.drawImage(img, -img.width, 0, img.width, img.height);
      break;
    default:
      canvas.width = img.width;
      canvas.height = img.height;
      ctx.drawImage(img, 0, 0, img.width, img.height);
      break;
  }
  return canvas.toDataURL("image/png");
}

Save the above code asrotate.js

When the rotation icon is clicked, this function is called, passing in the image object and the rotation angle:

import imageRotate from './rotate';
methods:{
    
    
	this.base64 = imageRotate(this.data, rotate);
}
// base64即为可直接显示图片的base64地址
<img :src="base64" />

There is no problem using the above in the vue project.

If you have difficulties in web front-end development, interviews, and front-end learning routes, you can add me V: imqdcnn. Answer questions for free, and technical experts who have been deep in the industry for many years will help you solve bugs.

I wish you can become an excellent WEB front-end development engineer!

Guess you like

Origin blog.csdn.net/imqdcn/article/details/131309328