Providing SvelteKit Canvas-D3 dashboard example
Here's a concise SvelteKit example showing how to combine D3 scales and axes with Canvas rendering of 50k points, plus a d3-quadtree for efficient hover detection. The Y and X axes use SVG with D3 axes, while Canvas draws the scatter points efficiently, with pointermove triggering quadtree search and hover effects. The rendering is hooked into Svelte's onMount to avoid SSR issues and uses requestAnimationFrame to maintain 60fps performance.
Below is a pattern you can use in SvelteKit to render 50K points at 60fps using Canvas for the scatterplot (or whichever point-based visualization you need), D3 for the scales and axes, and a D3 quadtree for efficient hover detection. You’ll keep the axes in SVG (so they’re crisp and easy to style) and use Canvas for the data points (for performance).
Key points:
- Use
onMount in Svelte to set up DOM references.
- Draw axes with D3 on SVG
<g> elements.
- Draw points with Canvas by mapping each datum through D3 scales.
- Build a D3 quadtree to quickly find the nearest point under the cursor.
- Handle pointer events on the Canvas; translate mouse coords to data-space, query the quadtree, and highlight the hovered point.
Example +page.svelte
<script lang="ts">
import { onMount } from 'svelte';
import * as d3 from 'd3';
// Example: generate 50k random points
const NUM_POINTS = 50000;
const data = Array.from({ length: NUM_POINTS }, () => ({
x: Math.random() * 1000,
y: Math.random() * 1000
}));
let containerEl: HTMLDivElement | null = null;
let svgEl: SVGSVGElement | null = null;
let canvasEl: HTMLCanvasElement | null = null;
// Dimensions and margins
const margin = { top: 20, right: 20, bottom: 40, left: 50 };
let width = 800;
let height = 500;
let xScale: d3.ScaleLinear<number, number>;
let yScale: d3.ScaleLinear<number, number>;
let quadtree: d3.Quadtree<{ x: number; y: number }>;
let hoveredPoint: { x: number; y: number } | null = null;
let hoverLabel: string | null = null;
// Redraw function for Canvas
function drawCanvas(points: typeof data) {
if (!canvasEl || !xScale || !yScale) return;
const ctx = canvasEl.getContext('2d');
if (!ctx) return;
// Clear canvas
ctx.clearRect(0, 0, canvasEl.width, canvasEl.height);
// Draw points
ctx.fillStyle = '#3498db';
ctx.beginPath();
for (const d of points) {
const cx = xScale(d.x);
const cy = yScale(d.y);
ctx.moveTo(cx + 1.5, cy);
ctx.arc(cx, cy, 1.5, 0, 2 * Math.PI);
}
ctx.fill();
// Optionally highlight hovered
if (hoveredPoint) {
ctx.fillStyle = 'orange';
const hx = xScale(hoveredPoint.x);
const hy = yScale(hoveredPoint.y);
ctx.beginPath();
ctx.arc(hx, hy, 4, 0, 2 * Math.PI);
ctx.fill();
}
}
// Build quadtree for fast nearest-neighbor
function buildQuadtree(points: typeof data) {
quadtree = d3.quadtree<{ x: number; y: number }>()
.x(d => d.x)
.y(d => d.y)
.addAll(points);
}
// Find the nearest point to mouse
function findNearest(mouseX: number, mouseY: number) {
if (!quadtree || !xScale || !yScale) return null;
// Convert screen coords back to data coords
const xVal = xScale.invert(mouseX);
const yVal = yScale.invert(mouseY);
// Search within a radius; start small and expand if needed
const radius = 10; // in screen space; can tune
const found = quadtree.find(xVal, yVal, radius);
return found || null;
}
// Draw axes
function drawAxes() {
if (!svgEl || !xScale || !yScale) return;
const svg = d3.select(svgEl);
const xAxis = d3.axisBottom(xScale);
const yAxis = d3.axisLeft(yScale);
// X Axis
svg.select<SVGGElement>('.x-axis')
.attr('transform', `translate(${margin.left}, ${height - margin.bottom})`)
.call(xAxis);
// Y Axis
svg.select<SVGGElement>('.y-axis')
.attr('transform', `translate(${margin.left}, ${margin.top})`)
.call(yAxis);
}
// Handle pointer move on canvas
function handlePointerMove(event: PointerEvent) {
if (!canvasEl || !xScale || !yScale) return;
const rect = canvasEl.getBoundingClientRect();
const mouseX = event.clientX - rect.left;
const mouseY = event.clientY - rect.top;
const nearest = findNearest(mouseX, mouseY);
hoveredPoint = nearest;
hoverLabel = nearest ? `x: ${nearest.x.toFixed(2)}, y: ${nearest.y.toFixed(2)}` : null;
// Redraw to highlight hovered
drawCanvas(data);
}
// On mount, set up scales, axes, and draw
onMount(() => {
if (!containerEl || !svgEl || !canvasEl) return;
// Make sure canvas matches container size
const containerRect = containerEl.getBoundingClientRect();
width = Math.max(600, containerRect.width);
height = 500;
canvasEl.width = width;
canvasEl.height = height;
// Scales
xScale = d3.scaleLinear()
.domain([0, 1000]) // or d3.extent(data, d => d.x)
.range([margin.left, width - margin.right]);
yScale = d3.scaleLinear()
.domain([0, 1000])
.range([height - margin.bottom, margin.top]);
// Build quadtree
buildQuadtree(data);
// Draw axes
drawAxes();
// Initial draw
drawCanvas(data);
});
</script>
<style>
.chart-container {
position: relative;
width: 100%;
overflow: hidden;
}
svg.axis-layer {
position: absolute;
top: 0;
left: 0;
pointer-events: none; /* ensures canvas gets pointer events */
}
canvas {
position: absolute;
top: 0;
left: 0;
}
.hover-label {
position: absolute;
top: 10px;
left: 10px;
background: rgba(255,255,255,0.85);
border: 1px solid #ddd;
padding: 4px 8px;
pointer-events: none;
font-size: 12px;
}
</style>
<div class="chart-container" bind:this={containerEl} style={`height:${height}px`}>
<!-- Canvas for points -->
<canvas
bind:this={canvasEl}
on:pointermove={handlePointerMove}
on:pointerleave={() => {
hoveredPoint = null;
hoverLabel = null;
drawCanvas(data);
}}
></canvas>
<!-- SVG just for axes -->
<svg class="axis-layer" bind:this={svgEl} width={width} height={height}>
<g class="x-axis"></g>
<g class="y-axis"></g>
</svg>
{#if hoverLabel}
<div class="hover-label">{hoverLabel}</div>
{/if}
</div>
How it works
-
Scales & Axes:
- We use
d3.scaleLinear for x and y.
- We draw axes on an SVG overlay using
d3.axisBottom and d3.axisLeft.
-
Canvas for Points:
drawCanvas loops through all data points, transforms them with the scales, and renders them on a <canvas>. Drawing 50k small circles at once should still be performant.
-
Quadtree for Hover:
d3.quadtree is built over the data using the x and y fields.
- On pointer move, convert the mouse position to data coordinates using the scale’s
invert and query quadtree.find(...) with a small radius to locate the nearest point.
-
Hover Highlighting:
- When you find a point, set
hoveredPoint, update hoverLabel, and call drawCanvas again to show the highlighted point in a different color.
-
Performance Tips:
- Keep the Canvas layer for heavy drawing (points, lines, shapes).
- Keep the SVG overlay for crisp axes and any textual labels.
- For 50k points, avoid re-binding data to the DOM. Use Canvas and D3 scales.
- Redraw only when needed (e.g., on pointer move or data update).
- If you need panning/zooming, you can integrate
d3.zoom to update scales and re-render.
This approach typically sustains 60fps with tens of thousands of points, leveraging Canvas for the main draw while preserving D3’s nice scale and axis utilities.