【发布时间】:2019-06-13 19:11:20
【问题描述】:
哦,嗨。我有一个 SVG,我正在将其转换为 png 并上传到服务器。只要我在 SVG 标签中明确给出宽度和高度值,一切都会正常工作。我使用 viewBox=" " 给 SVG 一个纵横比,没有宽度和高度属性,svg 可以很好地缩放到浏览器窗口中。因此,我不想在标签中包含宽度和高度。
以下是代码的相关部分:
var svg = document.querySelector( "svg" );
var svgData = new XMLSerializer().serializeToString( svg );
var nzs ="";
var canvas = document.createElement( "canvas" );
canvas.width = $('#mainSVG').width();// I tried giving the canvas a size, but it doesn't help
canvas.height = $('#mainSVG').height();
console.log(canvas.width +" " + canvas.height);
var ctx = canvas.getContext( "2d" );
var img = document.createElement( "img" );
img.setAttribute( "src", "data:image/svg+xml;base64," + btoa( svgData ) );
img.onload = function() {
ctx.drawImage( img, 0, 0);
// ctx.drawImage( img, 0, 0, $('#mainSVG').width(), $('#mainSVG').height() ); // I tried setting the image size in this line but it didn't work either.
nzs= canvas.toDataURL( "image/png" );
$.ajax({
url:"hidden.php",
data:{base64: nzs},
type:"post",
complete:function(){
console.log("Ready");
}
});
};
<svg id="mainSVG" clasxmlns="http://www.w3.org/2000/svg" viewBox="0 0 2800 1600">
<!-- <svg id="mainSVG" clasxmlns="http://www.w3.org/2000/svg" viewBox="0 0 2800 1600" width="800" height="1000"> If i use this tag everything works --!>
如何将动态创建的宽度和高度插入 SVG 标记?我想过操纵 svgData 字符串以包含宽度和高度属性,但这不是最简单的方法。提前谢谢你。
【问题讨论】:
标签: javascript svg png