import html2canvas from 'html2canvas'
import jpg from '@/assets/1.jpg';
htmlToImage=(element, callback)=> {
var width = element.offsetWidth;
var height = element.offsetHeight;
var canvas = document.createElement("canvas");
canvas.width = width ;
canvas.height = height ;
var context = canvas.getContext("2d");
var options = {
scale: scale,
canvas: canvas,
// logging: true,
width: width,
height: height,
taintTest: true, //在渲染前測試圖片
useCORS: true, //貌似與跨域有關,但和allowTaint不能共存
dpi: window.devicePixelRatio, // window.devicePixelRatio是設備像素比
background: "#fff",
};
html2canvas(element, options).then(function (canvas) {
var dataURL = canvas.toDataURL('image/jpeg', 0.5); //將圖片轉爲base64, 0-1 表示清晰度
console.log(dataURL)
var base64String = dataURL.toString().substring(dataURL.indexOf(",") + 1); //截取base64以便上傳
}
截圖的圖片
<img src={jpg} alt="" style={{width:'100%'}} className='aaa'/>
點擊截取
< Button onClick = {
() => this.htmlToImage(document.getElementsByClassName("aaa")[0])
} > 點擊截圖 </Button>