You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用D3.js制作骰子面组件后元素存在却不显示的问题

问题原因及解决办法

核心问题

你用d3.create("rect")创建的是无命名空间的rect元素,而SVG仅能识别属于SVG命名空间的元素。即便你将这个元素添加到SVG容器中,浏览器也无法正确渲染它——这就是为什么调试能看到rect标签,但页面上看不到图形的原因。

解决办法

有两种常见的修复方式:

方式一:指定SVG命名空间创建元素

修改dieFace函数中的rect创建代码,给d3.create加上SVG命名空间参数:

function dieFace(d){
  const elt = d3.create("rect", d3.namespaces.svg) // 新增命名空间参数
    .attr("x", 10 + 200 * d[0])
    .attr("y", 10 + 120 * d[1])
    .attr("width", 100)
    .attr("height", 100)
    .attr("rx", 24)
    .attr("ry", 24)
    .attr("fill", "#000")
    .attr("stroke-width", "5")
    .attr("stroke", "#000"); // 可选:显式设置描边颜色,确保描边可见

  return elt.node()
}

方式二:通过父SVG元素创建rect(更符合D3习惯)

调整dieFace函数,利用父元素(SVG容器)的append方法创建rect——这种方式会自动继承SVG命名空间,无需手动指定:

function dieFace(d){
  return d3.select(this) // this指向父SVG容器
    .append("rect")
    .attr("x", 10 + 200 * d[0])
    .attr("y", 10 + 120 * d[1])
    .attr("width", 100)
    .attr("height", 100)
    .attr("rx", 24)
    .attr("ry", 24)
    .attr("fill", "#000")
    .attr("stroke-width", "5")
    .attr("stroke", "#000");
}

两种方式都能让浏览器正确识别并渲染骰子面的矩形,你可以根据自己的代码习惯选择。


内容的提问来源于stack exchange,提问作者Felix Benning

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.15 03:38:12