0 day streak
javascript / expert
Snippet

Orchestrating Imperative Canvas Rendering via $effect

When dealing with imperative APIs like HTML5 Canvas, $effect serves as the bridge. Any change to 'color' or 'position' (if they are reactive runes) will trigger the effect, allowing for high-performance visual synchronization between state and pixels.

snippet.js
javascript
1
2
3
4
5
6
$effect(() => {
const ctx = canvasElement.getContext('2d');
ctx.clearRect(0, 0, 500, 500);
ctx.fillStyle = color;
ctx.fillRect(position.x, position.y, 50, 50);
});
svelte
Breakdown
1
canvasElement.getContext('2d');
Obtains the drawing context for the imperative API.
2
ctx.clearRect(0, 0, 500, 500);
Resets the frame before the next reactive draw cycle.
3
ctx.fillRect(position.x, position.y, 50, 50);
Draws the element using the current values of reactive state.