I think the "canvas" element is treated as unknown "canvas" element of SVG by d3.
(我认为d3将“画布”元素视为SVG的未知“画布”元素。)
So the "canvas" element is not mapped to HTMLCanvasElement
but SVGUnknownElement
in domtree of document, thus getContext()
of SVGUnknownElement
is undefined
.(因此,“画布”元素未映射到HTMLCanvasElement
但SVGUnknownElement
中的文件domtree,从而getContext()
的SVGUnknownElement
是undefined
。)
To solve this problem, you should wrap the "canvas" element by foreignObject
element and add xhtml
namespace to the "canvas" element.
(要解决此问题,您应该用foreignObject
元素包装“ canvas”元素,然后将xhtml
命名空间添加到“ canvas”元素中。)
I'm not good at d3, please try to construct this structure by using d3.
(我不擅长d3,请尝试使用d3构造此结构。)
<g class="node" transform="translate(210,330)">
<foreignObject x="-8" y="-8">
<canvas id="0_0" xmlns="http://www.w3.org/1999/xhtml"></canvas>
</foreignObject>
</g>
Or use image element instead of "canvas" element to put image created by (html)canvas element.
(或使用image元素代替“ canvas”元素来放置由(html)canvas元素创建的图像。)
SVG structure
(SVG结构)
<g class="node" transform="translate(210,330)">
<image x="-8" y="-8" id="0_0"/>
</g>
Javascript code
(JavaScript代码)
//create canvas element.
//var canvas = document.getElementById(nodes[i].__data__.name);
var canvas = document.createElement("canvas");
//console.log(canvas, canvas.nodeName);
var ctx = canvas.getContext('2d');
canvas.width = width;
canvas.height = height;
var idata = ctx.createImageData(width, height);
idata.data.set(buffer);
ctx.putImageData(idata, 0, 0);
//set image created by canvas to image element.
var image = document.getElementById(nodes[i].__data__.name);
image.width.baseVal.value = width;
image.height.baseVal.value = height;
image.href.baseVal = canvas.toDataURL();
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…