跳至主要內容

你可以使用特殊的 bind:this 指令來取得元件中元素的唯讀綁定。

此練習中的 $effect 嘗試建立一個畫布上下文,但 canvasundefined。首先在元件頂層宣告它...

App
<script>
	import { paint } from './gradient.js';

	let canvas;

	$effect(() => {
		// ...
	});
</script>

...然後將指令新增到 <canvas> 元素

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

請注意,canvas 的值在元件掛載之前會保持 undefined — 換句話說,您在 $effect 執行之前無法存取它。

在 GitHub 上編輯此頁面

上一頁 下一頁
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
<script>
	import { paint } from './gradient.js';
 
	$effect(() => {
		const context = canvas.getContext('2d');
 
		let frame = requestAnimationFrame(function loop(t) {
			frame = requestAnimationFrame(loop);
			paint(context, t);
		});
 
		return () => {
			cancelAnimationFrame(frame);
		};
	});
</script>
 
<canvas width={32} height={32}></canvas>
 
<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: 60vmin;
		-webkit-mask: url(./svelte-logo-mask.svg) 50% 50% no-repeat;
		-webkit-mask-size: 60vmin;
	}
</style>