DOM to Canvas如何获取要渲染的图像

时间:2018-09-04 02:41:25

标签: reactjs canvas png html2canvas

我正在使用此代码将React组件保存到png图像中。

import ReactDOMServer from 'react-dom/server';

export default class SvgToImgHelper{

    static canvas=null;
    static context=null;

    static getContext(){
        if (!SvgToImgHelper.context){
            SvgToImgHelper.canvas=document.createElement('canvas');
            SvgToImgHelper.canvas.height=800;
            SvgToImgHelper.canvas.width = 400;

            SvgToImgHelper.context= SvgToImgHelper.canvas.getContext('2d');
            SvgToImgHelper.context.font="Arial";
        }
        return SvgToImgHelper.context;

    }
    static getImage(element,w,h,imgId){
        let text=ReactDOMServer.renderToStaticMarkup(element)

        text= `<svg xmlns="http://www.w3.org/2000/svg"  xmlns:xlink="http://www.w3.org/1999/xlink" width="${w*2}" height="${h*2}"  viewBox="0 0 ${w} ${h}"  style="font-family: Arial;"> 
        <foreignObject width="${w}" height="${h}"><div xmlns="http://www.w3.org/1999/xhtml">${text}</div></foreignObject></svg>`
        text=encodeURIComponent(text)
        let domURL = self.URL || self.webkitURL || self;

        var img =new Image();
        img.onload = function() {
            let ctx =SvgToImgHelper.getContext();
            SvgToImgHelper.canvas.height=h*2;
            SvgToImgHelper.canvas.width = w*2;

            ctx.clearRect(0,0,w*2,h*2);
            ctx.drawImage(img, 0, 0);
            var png = SvgToImgHelper.canvas.toDataURL("image/png",1.0);
            let svgImg=document.getElementById(imgId)
            if (svgImg){
                svgImg.src =png;

            }

            domURL.revokeObjectURL(png);

        };
        img.onerror = function(e) {
            console.log(e.error)
        };
        img.src = "data:image/svg+xml," + text;
    }



    static clearURl(url){
        return domURL.revokeObjectURL(url);
    }
}

我的问题是具有图像的组件。 图像未保存为png。有人知道如何将具有图片的DOM元素保存为png吗?

0 个答案:

没有答案