Public
Edited
Feb 9, 2024
Fork of Simple D3
1 fork
Insert cell
Insert cell
chart = {
// const width = 928; // uncomment for responsive width
const height = 800;
const svg = d3
.create("svg")
.attr("viewBox", [0, 0, width, height])
.attr("width", width)
.attr("height", height)
.attr("style", "max-width: 100%; height: auto;")
.attr("transform", "rotate(20deg)");

var squareSize = 6;
var padding = 2;

// Create rows
const puzzles = svg
.selectAll(".row")
.data(data)
.enter()
.append("g")
.attr("class", "row")
.attr("transform", (d, i) => `translate(0, ${i * (squareSize + padding)})`);

// Create squares within each row
const squares = puzzles
.selectAll(".square")
.data((d) => Object.values(d))
.enter()
// .filter(function (d) {
// console.log(d);
// d !== null && d !== "";
// })
.append("rect")
.attr("class", (d) => `square ${d}`) // (d) => `square ${d}`)
.attr("x", (d, i) => i * (squareSize + padding))
.attr("width", squareSize)
.attr("height", squareSize)
.attr("cell-index", (d) => d)
.attr("grid-section", (d) => getSudokuSection(d))
.attr("fill", "#d3d3d3")
.attr("display", (d) => (d === null ? "none" : "block"))

// hover events
.on("mousemove", function (event, d) {
var activeCellIndex = d3.select(this).attr("cell-index");
var activeGridSection = getSudokuSection(activeCellIndex);

// highlight other cells from active section
d3.selectAll("rect[grid-section='" + `${activeGridSection}` + "'").attr(
"fill",
"#40C6F9"
);

// highlight active cell
d3.selectAll("rect[cell-index='" + `${activeCellIndex}` + "'").attr(
"fill",
"#08759E"
);
})

.on("mouseout", function (event, d) {
var activeCellIndex = d3.select(this).attr("cell-index");
var activeGridSection = getSudokuSection(activeCellIndex);

// highlight active cell
d3.selectAll("rect[cell-index='" + `${activeCellIndex}` + "'").attr(
"fill",
"#d3d3d3"
);

// un-highlight other cells from active section
d3.selectAll("rect[grid-section='" + `${activeGridSection}` + "'").attr(
"fill",
"#d3d3d3"
);
});

return svg.node();
}
Insert cell
function getSudokuSection(cellIndex) {
// Check if the index is within the valid range (0 to 80)
if (cellIndex < 0 || cellIndex > 80) {
throw new Error("Invalid index. Cell index should be between 0 and 80.");
}

// Calculate the row and column indices from the cell index
const rowIndex = Math.floor(cellIndex / 9);
const colIndex = cellIndex % 9;

// Determine the section based on the row and column indices
const sectionRow = Math.floor(rowIndex / 3);
const sectionCol = Math.floor(colIndex / 3);

// Calculate the section number
const sectionNumber = sectionRow * 3 + sectionCol;

// Return the section number (zero-indexed)
return sectionNumber;
}
Insert cell
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more