vue下canvas裁剪图片实例讲解

  TailoringImg(oMark) {

  // 设置三个canvas 分别为 canvas1 ,canvas2,canvas3

  // 每个canvas的作用 canvas1原始图片画布(页面中隐藏);

  // canvas2原图和裁剪结果之间转换;

  // canvas3裁剪之后的结果展示(页面中展示);

  let res2 = oMark['ImgUrl'];

  let that = this;

  return new Promise(function (resolve, reject) {

  //图片剪切处理

  var canvas1 = document.getElementById(oMark['canvas2']);

  var canvas3 = document.getElementById(oMark['canvas1']);

  canvas1.height = 1080;

  canvas1.width = 1920;

  canvas3.height = 198;

  canvas3.width = 400;

  var cxt1 = canvas1.getContext("2d"); // getContext() 方法返回一个用于在画布上绘图的环境

  var img = new Image();

  img.crossOrigin = '';

  img.src = res2;

  var canvas2 = document.createElement("canvas"); // 创建虚拟画布环境

  var cxt2 = canvas2.getContext("2d");

  img.onload = function () {

  // 计算图片缩放比例

  var Rwidth = canvas1.width / img.width;

  var Rheight = canvas1.height / img.height;

  cxt1.drawImage(img, 0, 0, canvas1.width, canvas1.height); // --第一步-- 原图绘制在画布上 drawImage方法在画布上绘制图像、画布或视频。也能够绘制图像的某些部分,以及/或者增加或减少图像的尺寸。

  // 计算缩放好后的尺寸

  var srcX = oMark.offsetLeft * Rwidth;

  var srcY = oMark.offsetTop * Rheight;

  var sWidth = oMark.offsetWidth * Rwidth;

  var sHeight = oMark.offsetHeight * Rheight;

  var dataImg = cxt1.getImageData(srcX, srcY, sWidth, sHeight); // --第二步-- getImageData() 复制原图画布上指定矩形的像素数据

  canvas2.width = sWidth;

  canvas2.height = sHeight;

  cxt2.putImageData(dataImg, 0, 0, 0, 0, canvas2.width, canvas2.height); // --第三步-- 通过 putImageData() 将原图图像数据放到canvas2画布中

  var img2 = canvas2.toDataURL("image/png"); // --第四步-- toDataURL()将canvas2画布保存为图像

  var cxt3 = canvas3.getContext("2d"); // getContext() 方法返回一个用于在画布上绘图的环境

  var img3 = new Image(); // 创建图像对象

  img3.crossOrigin = ''; // 图像跨域设置

  img3.src = img2; // 设置图像地址

  img3.onload = function () { // onload内可以获取图像信息

  cxt3.drawImage(img3, 0, 0, canvas3.width, canvas3.height) // --第五步-- 将canvas2画布生成的图像放在canvas3画布中

  };

  resolve();

  }

  })

  },