在網上看到的老是差一點,在此記錄一下本身須要的css
下邊都是 vue 模式代碼,須要注意註釋的地方是不能丟的
<!-- HTML 部分 --> <div class="op"> <div class="show-view" ref="showView"> <!-- 要抓取的 dom 部分 --> <p>這裏是文字文字叮噹的。。。。</p> <img src="圖片地址" alt=""> </div> </div> <div class="canvas-view"> <!-- 存放生成的圖片部分 --> <img :src="canvasSrc" alt=""> </div>
// css 部分 .op { opacity: 0; // 要隱藏要抓取 dom 部分,只能是設置到抓取 dom 的外層元素上。 .show-view img{ width: 200px; height: 300px; // 異步加載圖片高度必定要設置好,不然會抓取不到 } }
// 部分 js import html2canvas from 'html2canvas'; export default { data () { return { canvasSrc: '' } }, mounted () { let dom = this.$refs.showView; html2canvas(dom, { useCORS: true, // 有異步加載部分,例如圖片等 scale: 2, // 設備像素比,默認是設備的 devicePixelRatio height: dom.clientHeight, // 生成的 canvas 部分的高度 width: dom.clientWidth // 生成的 canvas 部分的寬度 }).then(canvas => { // canvas 參數便是抓取的 show-view 部分dom生成的canvas,後邊是否須要生成圖片,看本身的需求 let src = canvas.toDataURL(); // 調用 canvas 的方法,生成圖片 this.canvasSrc = src; }); } }