vue下canvas裁剪图片
由于时间关系 代码没有做整理大家有什么不懂得可以留言;
代码的主题思路备注中都有 大家可以看看
我的博客中还有关于canvas绘制矩形的文章有需要的可以看一下;
HTML代码:
第一行的canvas为裁剪后展示用;div中的canvas存放原有尺寸的图片
<canvas id="canvasImg1" style=" position: absolute; margin: 2px 0 0 0"></canvas> <div id="dymImgCanv1" style=" display:none;"> <canvas id="dymCurrImg1" :src="leftImg.carImgUrl" width="1920" height="1080"></canvas> </div>
JS截取图片方法
1裁剪方法传参
oMark2['canvas1'] = 'canvasImg2'; // 展示结果canvas id oMark2['canvas2'] = 'dymCurrImg2'; //画布原始图片canvas id oMark2['ImgUrl'] = carImgUrl; oMark2['offsetLeft'] = location[0]; oMark2['offsetTop'] = location[2]; oMark2['offsetWidth'] = location[1] - location[0]; oMark2['offsetHeight'] = location[3] - location[2];
2裁剪方法 (注意:下边方法中关于构建的画布 canvas1,canvas3与两个canvas标签ID的命名是不对应的,方便大家理解我把关系捋出来
canvas1 = oMark['canvas2'] = 'dymCurrImg2'
canvas3 = oMark['canvas1'] = 'canvasImg2'
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(); } }) },