Skip to main content

Part 3 / Advanced bindings / This

The readonly this binding applies to every element (and component) and allows you to obtain a reference to rendered elements. For example, we can get a reference to a <canvas> element:

App.svelte
<canvas
	bind:this={canvas}
	width={32}
	height={32}
></canvas>

Note that the value of canvas will be undefined until the component has mounted, so we put the logic inside the onMount lifecycle function.

Next: Component bindings

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
<script>
	import { onMount } from 'svelte';
 
	let canvas;
 
	onMount(() => {
		const ctx = canvas.getContext('2d');
		let frame = requestAnimationFrame(loop);
 
		function loop(t) {
			frame = requestAnimationFrame(loop);
 
			const imageData = ctx.getImageData(
				0,
				0,
				canvas.width,
				canvas.height
			);
 
			for (
				let p = 0;
				p < imageData.data.length;
				p += 4
			) {
				const i = p / 4;
				const x = i % canvas.width;
				const y = (i / canvas.width) >>> 0;
 
				const r =
					64 +
					(128 * x) / canvas.width +
					64 * Math.sin(t / 1000);
				const g =
					64 +
					(128 * y) / canvas.height +
					64 * Math.cos(t / 1000);
				const b = 128;
 
				imageData.data[p + 0] = r;
				imageData.data[p + 1] = g;
				imageData.data[p + 2] = b;
				imageData.data[p + 3] = 255;
			}
 
			ctx.putImageData(imageData, 0, 0);
		}
 
		return () => {
			cancelAnimationFrame(frame);
		};
	});
</script>
 
<canvas width={32} height={32} />
 
<style>
	canvas {
		position: fixed;
		left: 0;
		top: 0;
		width: 100%;
		height: 100%;
		background-color: #666;
		mask: url(svelte-logo-mask.svg) 50% 50% no-repeat;
		mask-size: 40%;
		-webkit-mask: url(svelte-logo-mask.svg) 50% 50% no-repeat;
		-webkit-mask-size: 40%;
	}
</style>
 
initialising