【发布时间】:2018-04-29 18:16:39
【问题描述】:
我的程序动态生成 SVG 对象,我可以通过将它们添加到 DOM 来可视化它们。
我也想在 HTML5 画布上绘制它们,但尽管在网络上搜索失败,但到目前为止还是失败了。对绘制实际源文件的 SVG 的支持很丰富,但就我目前所能找到的而言,不支持动态创建的 SVG。
我的尝试如下代码所示:
// dynamically create an svg containing a black circle
var svgns = "http://www.w3.org/2000/svg";
var svg = document.createElementNS (svgns, "svg");
svg.setAttribute ( "width" , "128" );
svg.setAttribute ( "height" , "128" );
svg.setAttributeNS ("http://www.w3.org/2000/xmlns/", "xmlns:xlink", "http://www.w3.org/1999/xlink");
shape = document.createElementNS (svgns, "circle");
svg.appendChild (shape);
shape.setAttribute ( "cx", 64);
shape.setAttribute ( "cy", 64);
shape.setAttribute ( "r", 50);
shape.setAttribute ( "fill", "black");
// add the svg to the DOM
document.body.appendChild (svg); // works
// create a canvas to render the black circle
var canvas = document.createElement ("canvas");
document.body.appendChild (canvas);
canvas.width = 300 ; canvas.height = 150 ;
var ctx = canvas.getContext ("2d");
// create an image to contain the svg data
var img = new Image ();
img.onload = function () { ctx.drawImage (this,10,10) };
// ATTEMPT 1
var svgURL = new XMLSerializer().serializeToString (svg);
img.src = "data:image/svg+xml; charset=utf8," + encodeURIComponent (svgURL); // does not work
// ATTEMPT 2
var xml = (new XMLSerializer()).serializeToString (svg);
img.src = "data:image/svg+xml;base64," + btoa (xml); // also does not work
// ATTEMPT 3
var hiddenDiv = document.createElement("div");
hiddenDiv.appendChild (svg.cloneNode(true));
img.src = "data:image/svg+xml;base64," + window.btoa (hiddenDiv.innerHTML); // also deos not work
顺便问一下,如果你问为什么不直接将对象绘制到画布上而不是创建 SVG,那是我也想在 DOM 中使用 svg。
【问题讨论】:
-
看看fabricjs
-
只有通过阅读,我在您的代码中看到的唯一错误是 xlink 名称空间解析器。但是你甚至不需要这个属性,所以不要设置它。
-
实际上即使出现此错误,您的第一次尝试在我的 FF 和 Android 上的 chrome 上都可以正常工作。 jsfiddle.net/1by04Lb5你用什么浏览器?
-
Chrome 测试
-
这令人费解。我现在再次尝试了我的第一次尝试并且它有效。我很抱歉浪费你的时间。关于你提到的错误,我是直接去掉那行代码,还是去掉xlink参数?
标签: javascript canvas svg