点击一个按钮,截取对应区域的界面,才对截取的界面进行裁切并下载
下载 html2canvas npm install html2canvas --save
引用 :
import html2canvas from 'html2canvas'
components: {
html2canvas
},
将你需要截取的部分用 id 包裹起来
<div id="capture" ref="imageTofile">......</div>
获取该区域
html2canvas(document.querySelector("#capture")).then(canvas => {
const imgUrl = canvas.toDataURL("png"); // 获取生成的图片的url
console.log(imgUrl)
})
这样就可以得到你需要需要截取的屏幕区域了
如果你需要再次对这样图片进行裁切
const img = new Image();
img.src = canvas.toDataURL("png");
img.setAttribute('crossOrigin', 'anonymous');
var canvas = document.createElement("canvas");//1. 获取画布
const num = this.dataLength * 48 + 148;
console.log(canvas)
canvas.width = 530;//这个设置不能丢,否者会成为canvas默认的300*150的大小
canvas.height = 500;//这个设置不能丢,否者会成为canvas默认的300*150的大小
var ctx = canvas.getContext("2d");//2. 获取画布上下文
img.onload=function() {
var w = img.width
var h = img.height
ctx.drawImage(img, 0, 0, w, h, 0, 0, w, h)
var dataURL = canvas.toDataURL("image/png");
console.log('裁切后',dataURL)
saveFile(dataURL,'images.jpg');// 下载图片
}
下载图片
var saveFile = function(data, filename){
var save_link = document.createElementNS('http://www.w3.org/1999/xhtml', 'a');
save_link.href = data;
save_link.download = filename;
var event = document.createEvent('MouseEvents');
event.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
save_link.dispatchEvent(event);
}