首页 > 解决方案 > DOM to Canvas 如何获取要渲染的图像

问题描述

我正在使用此代码将反应组件保存到 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。有谁知道如何保存具有 png 图像的 DOM 元素?

标签: reactjscanvaspnghtml2canvas

解决方案


推荐阅读