0 day streak
javascript / intermediate
Snippet

Referencing DOM Elements with bind:this

While Svelte is declarative, sometimes you need direct access to a DOM element (e.g., for Canvas or third-party libraries). The bind:this directive assigns the rendered element to a variable.

snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
<script>
let canvas;
function init() {
const ctx = canvas.getContext('2d');
ctx.fillRect(0, 0, 50, 50);
}
</script>
<canvas bind:this={canvas}></canvas>
svelte
Breakdown
1
let canvas;
Declares a variable that will hold the reference to the DOM element.
2
bind:this={canvas}
Tells Svelte to set the 'canvas' variable to this specific DOM element after it is created.
3
canvas.getContext('2d')
Directly calls standard browser APIs on the referenced element.