【发布时间】: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