使用html2canvas將頁面轉成圖,用canvas2image下載

cason6810發表於2019-03-26

之前在網上找到一個用 <a> 的 download屬性下載的方法,確實很簡單也很方便,但此方法不支援IE,無奈又找到另一方法。

使用html2canvas將頁面轉成圖,用canvas2image下載

本例使用的版本:

html2canvas@1.0.0-alpha.12
canvas2image@1.0.5

安裝

npm install html2canvas canvas2image --save

引入

import html2canvas from 'html2canvas';
require('./canvas2image.js');

canvas2image.js 需要改動一下,以便綁在window上

(function($){
    Canvas2Image = function () {
    ...
    }
}

_dataURL 可以用來回顯,Canvas2Image.saveAsPNG(canvas) 會直接下載。
Canvas2Image提供了下面幾種方法:

Canvas2Image.saveAsImage(canvasObj, width, height, type)
Canvas2Image.saveAsPNG(canvasObj, width, height)
Canvas2Image.saveAsJPEG(canvasObj, width, height)
Canvas2Image.saveAsGIF(canvasObj, width, height)
Canvas2Image.saveAsBMP(canvasObj, width, height)

Canvas2Image.convertToImage(canvasObj, width, height, type)
Canvas2Image.convertToPNG(canvasObj, width, height)
Canvas2Image.convertToJPEG(canvasObj, width, height)
Canvas2Image.convertToGIF(canvasObj, width, height)
Canvas2Image.convertToBMP(canvasObj, width, height)

在vue中可以用$refs 確定DOM;
backgroundColor: null,此句可使轉出的圖沒有白邊

        methods: {
            toImage() {
                let _this = this;
                html2canvas(this.$refs.index,{
                    backgroundColor: null
                }).then((canvas) => {
                    let _dataURL = canvas.toDataURL("image/png");                    
                    // _this.dataURL = _dataURL;
                    Canvas2Image.saveAsPNG(canvas)
                });
            },

相關文章