【问题标题】:Uncaught TypeError: canvas.node(...).getContext is not a function未捕获的类型错误:canvas.node(...).getContext 不是函数
【发布时间】:2021-03-08 19:54:47
【问题描述】:

我使用 svg 用 d3 构建了一个集群力布局气泡图(在桌面上效果很好)。我想做的是将我的代码转换为画布,因为它在移动设备上变得相当滞后。

这是我第一次真正尝试使用 canvas api,所以我不确定我的做法是否正确。 (可能不是)。当我运行我的代码时,我在控制台中收到以下错误消息。

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

这是我的原始代码 (svg),效果很好。

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

  ....

这是破坏的画布代码:

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

  ....

TypeError 指的是这一行:

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

任何帮助将不胜感激。

【问题讨论】:

  • var canvas 指向 g 子元素,而不是由于 d3 链接的 canvas 元素。

标签: javascript svg d3.js canvas data-visualization


【解决方案1】:

忽略&lt;canvas&gt; 没有viewBox&lt;g&gt; 元素的事实,当你这样做时......

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

...您的canvas 选择实际上是g 元素,它显然没有getContext 方法。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-11-19
    • 1970-01-01
    • 2019-06-06
    • 2019-05-24
    • 2021-12-15
    • 2019-10-26
    • 2016-06-27
    相关资源
    最近更新 更多