reactjs - 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 元素?
解决方案
推荐阅读
- angularjs - 在角度 JS 中注销后防止返回按钮
- iis - 502 - Web 服务器在充当网关或代理服务器时收到无效响应。IIS
- c++ - 如何在 C++ 中创建不同数量的线程?
- python - 使用 openweather API 将 json 加载到 pandas 数据框
- typo3 - 切换域后无法登录后台
- angular - 在迁移到 Angular 9 期间中断服务
- tensorflow - 与门单层神经网络与张量流
- sql-server - 如何在 Entity Framework Core 中使用 FromSql 将值列表作为 Sql 参数传递
- c++ - 使用 STL 的简单视图
- amp-html - 将 GDPR 同意字符串传递到 amp-iframe