【问题标题】:Legend not appearing when using document.createElement('canvas')使用 document.createElement('canvas') 时未出现图例
【发布时间】:2020-06-12 01:32:03
【问题描述】:

我关注了this Observable 的帖子以轻松创建图例。

自行

DOM.canvas(1, n)

ramp 中仅适用于 Observable,我将其替换为

document.createElement("canvas")

还修改了 SVG 以便将其附加到主 div 标签。这些更改不会导致任何错误,但问题是即使图例 SVG 存在于原始 HTML 中,也不会显示图例。

这是 JSFiddle 的 link。任何指导将不胜感激。

【问题讨论】:

  • 嗨。如果您是新手,请take the Tour(这样做会获得徽章)并学习How to ask a good question。在寻求调试帮助时,请始终包含重现问题所需的最少代码in the question itself(指向 JSFiddle 的链接是次要的)
  • @blex 感谢您的链接,您对如何改进我的问题有具体建议吗?
  • 在寻求调试帮助时,请始终在问题本身中包含重现问题所需的最少代码
  • @blex 我是否包含太多代码?
  • 您没有包含任何代码。相反,您包含了代码链接

标签: javascript d3.js svg canvas observablehq


【解决方案1】:

画布正在创建中,这不是问题。问题是,由于您现在缺少...的宽度和高度...

const canvas = DOM.canvas(n, 1);
//these are w & h --------^--^

...您现在需要自己设置这些。例如:

d3.select(canvas).attr("width", n)
  .attr("height", 1);

这是 JSFiddle 的简化版本,显示画布可以正常工作:

legend({
  color: d3.scaleSequential([1, 10], d3.interpolateReds),
  title: "Title"
})


function legend({
  color,
  title,
  tickSize = 6,
  width = 320,
  height = 44 + tickSize,
  marginTop = 18,
  marginRight = 0,
  marginBottom = 16 + tickSize,
  marginLeft = 0,
  ticks = width / 64,
  tickFormat,
  tickValues
} = {}) {

  const svg = d3.select(".scatter").append("svg")
    .attr("width", width)
    .attr("height", height)
    .attr("viewBox", [0, 0, width, height])
    .style("overflow", "visible")
    .style("display", "block");

  svg.append("image")
    .attr("x", marginLeft)
    .attr("y", marginTop)
    .attr("width", width - marginLeft - marginRight)
    .attr("height", height - marginTop - marginBottom)
    .attr("preserveAspectRatio", "none")
    .attr("xlink:href", ramp(color.interpolator()).toDataURL());

}

function ramp(color, n = 256) {
  const canvas = document.createElement('canvas');
  const context = canvas.getContext("2d");
  d3.select(canvas).attr("width", n)
    .attr("height", 1);
  for (let i = 0; i < n; ++i) {
    context.fillStyle = color(i / (n - 1));
    context.fillRect(i, 0, 1, 1);
  }
  return canvas;
}
<script type="text/javascript" src="https://d3js.org/d3.v5.js"></script>
<div class="scatter">
</div>

顺便说一句,没有&lt;legend-svg&gt;这样的元素。


PS:这是你的second question,我正在回答这个问题。由于您是 JavaScript 和 D3 的新手,这里有一个建议:不要尝试使用那个 Observable 笔记本,这对于您的目的来说太复杂了。只需自己创建 SVG、画布和基本轴,从头开始,会容易得多。

【讨论】:

  • 感谢我正在寻找的简单修复。此外,感谢您的建议,我会牢记这一点!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-07-23
  • 2012-06-21
  • 2022-10-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多