我有一个SVG,我正在使用下面的JavaScript代码转换为PNG
$(".exportImageButton").on("click",function(){ var svg = document.querySelector( "svg" ); var svgData = new XMLSerializer().serializeToString( svg ); var canvas = document.createElement( "canvas" ); var svgSize = svg.getBoundingClientRect(); canvas.width = svgSize.width * 3; canvas.height = svgSize.height * 3; canvas.style.width = svgSize.width; canvas.style.height = svgSize.height; var ctx = canvas.getContext( "2d" ); ctx.scale(3,3); var img = document.createElement( "img" ); img.setAttribute( "src", "data:image/svg+xml;base64," + btoa(unescape(encodeURIComponent(svgData))) ); img.onload = function() { ctx.drawImage( img, 0, 0 ); var canvasdata = canvas.toDataURL("image/png",1); var pngimg = ''; d3.select("#pngdataurl").html(pngimg); var a = document.createElement("a"); a.download = "download_img"+".png"; a.href = canvasdata; document.body.appendChild(a); a.click(); };
但是我想在将svg元素转换为png之前对其进行更改。另外,我也不想在屏幕上向用户显示变化。
我只想向x轴标签添加不透明度1并转换为png,并让屏幕上的svg保持不变,而x轴标签的不透明度为0。
我怎样才能做到这一点 。任何帮助表示赞赏。
正如罗伯特建议的那样,就做吧...
$(".exportImageButton").on("click", function() {
var svg = document.querySelector("svg");
var rect = document.querySelector("rect")
rect.setAttribute("fill", "green")
var svgData = new XMLSerializer().serializeToString(svg);
var canvas = document.createElement("canvas");
var svgSize = svg.getBoundingClientRect();
canvas.width = svgSize.width * 3;
canvas.height = svgSize.height * 3;
canvas.style.width = svgSize.width;
canvas.style.height = svgSize.height;
var ctx = canvas.getContext("2d");
ctx.scale(3, 3);
var img = document.createElement("img");
img.setAttribute("src", "data:image/svg+xml;base64," + btoa(unescape(encodeURIComponent(svgData))));
rect.setAttribute("fill", "red")
img.onload = function() {
ctx.drawImage(img, 0, 0);
var canvasdata = canvas.toDataURL("image/png", 1);
var pngimg = '';
d3.select("#pngdataurl").html(pngimg);
var a = document.createElement("a");
a.download = "download_img" + ".png";
a.href = canvasdata;
document.body.appendChild(a);
a.click();
};
})