纯样式或使用JS的canvas实现图片旋转

效果如图:

image-20230131142927615

点击旋转,图片也跟着旋转。共有4个方向,分别是0,90,180,270度。

一、CSS3实现

如果是按照我的思路,那自然就是使用CSS3transformrotate属性了。

img{
    
    
    transform:rotate(90deg);
}

实际情况也是可以旋转的,简单方便,只适用于临时查看。

二、JS的canvas实现

原理大致是,将img图片转为canvas对象,输出新的图片路径,回显到img标签中。

大致的代码如下:

/** 图片旋转后返回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");
}

将以上代码保存为rotate.js

当点击旋转图标时,调用该函数,传入图片对象和旋转角度:

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

以上在vue项目中使用无任何问题。

如果你在web前端开发、面试、前端学习路线有困难可以加我V:imqdcnn。免费答疑,行业深潜多年的技术牛人帮你解决bug。

祝你能成为一名优秀的WEB前端开发工程师!

猜你喜欢

转载自blog.csdn.net/imqdcn/article/details/131309328
今日推荐