图片旋转-canvas drawImage拉伸问题

953 阅读1分钟

技术栈

react 17

需求描述

h5/app中上传图片位置不对,需要用户自己旋转图片调整正确上传

问题分析

Snipaste_2021-05-14_16-28-40.png

弹出预览层

dom 保存弹出层以便关闭删除
CanvasDom 旋转预览层 自己去写样式就好了
ReactDOM.render(<CanvasDom el={this} />, this.dom);

canvas保存图片

  /**
   * 完成调用函数
   * @param {*} num 旋转角度
   * @param {*} file 上的源文件
   * @param {*} callback 执行的回调函数
   *
   * @returns 旋转之后的文件图片
   */
  finally(num, file, callback) {
    const image = document.querySelector('#image');

    const imageFiles = URL.createObjectURL(file);
    const canvas = document.querySelector('#canvas');
    const eWidth = image.clientWidth * 2;
    const eHeight = image.clientHeight * 2;
    canvas.width = eWidth;
    canvas.height = eHeight;

    const ctx = canvas.getContext('2d');
 
    ctx.translate(eWidth / 2, eHeight / 2);
    ctx.rotate(num * (Math.PI / 180));
    ctx.translate(-eWidth / 2, -eHeight / 2);

    const imageMap = new Image();

    imageMap.onload = () => {
      ctx.drawImage(image, 0, 0, eWidth, eHeight);
      this.close();
      callback(dataURLtoFile(canvas.toDataURL(), file.name));
    };
    imageMap.src = imageFiles;
  }

拓展问题

当上传的图片无法知道尺寸大小怎么办?

解决方案

设置一个你想要压缩大小的宽度,通过一个img标签设置src为上传图片地址(如果是文件可以用 URL.createObjectURL 这个api转) 设置宽度(一定要放进页面中,之后悄悄藏起来),当你获取这个img属性的时候浏览器自动帮你设置好了高度,把这个高度和宽度丢给canvas就可以完美解决了,nice !!!