使用 document.createElement('canvas') 时不显示图例

Legend not appearing when using document.createElement('canvas')

我关注了thisObservablepost轻松创造了一个传奇。

因为行

DOM.canvas(1, n)

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

document.createElement("canvas")

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

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

正在创建 canvas,这不是问题所在。问题是,由于您现在缺少...

中的宽度和高度
const canvas = DOM.canvas(n, 1);
//these are w & h --------^--^

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

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

这是该 JSFiddle 的简化版本,表明 canvas 有效:

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>

顺便说一句,没有<legend-svg>这样的元素。


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