🏠 back to Observable

Continue drawing upon an SVG created in a different cell

In https://observablehq.com/d/4e5d48b692f468e6,
I created a cell which contains a function drawChessboard() which draws a SVG with a chess board.
I would like to add pieces or paths to this SVG in a different cell. How do I correctly reference that SVG in order to continue drawing upon it.

What I did was this cell:
{
const svg = drawChessboard();
const dataArray = […piecePositions.values()];

d3.select(“svg”)
// d3.selectAll(".chess-translate")
.selectAll(“path.piece-move”)
.data(dataArray)
.join(“path”)
.attr(“class”, “piece-move”)
.attr(“d”, d => d)
.style(“stroke”, (d, i) => (i < 16) ? “orange” : “steelblue”)
.style(“stroke-width”, 5)
.style(“stroke-linejoin”, “round”)
.style(“fill”, “none”);

/*
const pos = squareToPosition(“e4”);
d3.select(“svg”)
.append(“circle”)
.style(“fill”, “orange”)
.attr(“cx”, pos.x)
.attr(“cy”, pos.y)
.attr(“r”, 30);
*/

return svg;
}

However, the command d3.select(“svg”) does not seem to be the right selection to continue drawing since it doesn’t know which SVG is right one.

The experience was surprising, in one cell which this code it worked in a different one it doesn’t. Then I added something, later deleted, now it does not show anything more than the chessboard.

Initially it showed the desired result:

Note that there’s a difference between d3.select("svg") (with quotes, which selects the first svg element on the page) and d3.select(svg) (without quotes, which selects the element referenced by the svg variable). I believe you want the latter in this case.

Also, apologies for the self-promotion, but you might be interested in this notebook I made which demonstrates how to use two chess-related libraries in Observable:

1 Like

Yes, thanks so much, that was the trick I was missing.

I looked at the your notebook - wonderful - thanks so much for sharing! I will look into that more deeply and learn a lot by how you made it available on observable.
I am aware of these great libraries (chess.js and chessboard.js) - I was also already using chess.js to process games. What I try to do is experiment with a novel artful static visualization of the whole game.

1 Like

Further reading on selecting elements (and mutation):

See also:

1 Like