Skip to main content

之前的练习 中,我们学习了如何使用 onMount 生命周期函数绘制画布。

但是那个例子中有个小 bug,因为使用了 document.querySelector('canvas'),所以它总是会返回页面上找到的第一个 canvas 元素,有时候这可能并不是你需要的那个。

现在,我们可以使用一个只读的 this 绑定来获取元素的索引:

App.svelte
let canvas;

onMount(() => {
	const canvas = document.querySelector('canvas')
	const context = canvas.getContext('2d');

	let frame = requestAnimationFrame(function loop(t) {
		frame = requestAnimationFrame(loop);
		paint(context, t);
	});

	return () => {
		cancelAnimationFrame(frame);
	};
});
App.svelte
<canvas
	bind:this={canvas}
	width={32}
	height={32}
></canvas>

注意,在组件初始化之前,canvas 都是 undefined 的。

Next: 组件绑定

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
<script>
	import { onMount } from 'svelte';
	import { paint } from './gradient.js';
 
	onMount(() => {
		const canvas = document.querySelector('canvas')
		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>
 
initialising