canvas.getContext is not a function, when called on canvas

I think the "canvas" element is treated as unknown "canvas" element of SVG by d3. So the "canvas" element is not mapped to HTMLCanvasElement but SVGUnknownElement in domtree of document, thus getContext() of SVGUnknownElement is undefined.

To solve this problem, you should wrap the "canvas" element by foreignObject element and add xhtml namespace to the "canvas" element.

I'm not good at d3, please try to construct this structure by using 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.

SVG structure

<g class="node" transform="translate(210,330)">
  <image x="-8" y="-8" id="0_0"/>
</g>

Javascript code

//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();