bullybear17
bullybear17

Reputation: 889

Uncaught TypeError: canvas.node(...).getContext is not a function

I built a clustered force layout bubble chart with d3 using svg (works great on desktop). What I would like to do is convert my code to canvas as it gets quite laggy on mobile.

This is my first time really experimenting with the canvas api so I'm not sure if how I am going about this is the right way. (It probably isn't). When I run my code, I get the following error message in the console.

Uncaught TypeError: canvas.node(...).getContext is not a function

Here is my original code (svg) that works just fine.

HTML:

<div id="happyBubble"></div>

JS:

  var svg = d3.select("#happyBubble").append("svg")
    .attr("class", "forceTransitionHappy")
    .attr("viewBox", '0 -50  1250 1250')
    .append("g")
    .attr("transform", "translate(" + -50 + "," + -150 + ")");

  var node = svg.selectAll(".node")
    .data(nodes)
    .enter()
    .append("g")
    .attr("class", "node")
    .call(force.drag);

  ....

Here is the canvas code that breaks:

HTML:

<div id="happyBubble"></div>

JS:

  var canvas = d3.select("#happyBubble").append("canvas")
    .attr("class", "forceTransitionHappy")
    .attr("viewBox", '0 -50  1250 1250')
    .append("g")
    .attr("transform", "translate(" + -50 + "," + -150 + ")");

  var context = canvas.node().getContext("2d");

  var node = context.selectAll(".node")
    .data(nodes)
    .enter()
    .append("g")
    .attr("class", "node")
    .call(force.drag);

  ....

The TypeError is referring to this line:

var context = canvas.node().getContext("2d");

Any help would be immensely appreciated.

Upvotes: 1

Views: 544

Answers (1)

Gerardo Furtado
Gerardo Furtado

Reputation: 102198

Ignoring the fact that <canvas> don't have viewBox or <g> elements, when you do this...

var canvas = d3.select("#happyBubble").append("canvas")
    .attr("class", "forceTransitionHappy")
    .attr("viewBox", '0 -50  1250 1250')
    .append("g")

... your canvas selection is actually the g element, which obviously has no getContext method.

Upvotes: 2

Related Questions