Skip to main content
基本 Svelte
介绍
反应性
属性
逻辑
事件
绑定
类和样式
动作
转换
高级 Svelte
高级反应性
重用内容
运动
高级绑定
高级转换
上下文 API
特殊元素
<script module>
后续步骤
基本 SvelteKit
介绍
路由
加载数据
标题和 cookie
共享模块
表单
API 路由
$app/state
错误和重定向
高级 SvelteKit
钩子
页面选项
链接选项
高级路由
高级加载
环境变量
结论

你可以使用特殊的 bind:this 指令获取对组件中元素的只读绑定。

¥You can use the special bind:this directive to get a readonly binding to an element in your component.

本练习中的 $effect 尝试创建画布上下文,但 canvasundefined。首先在组件的顶层声明它...

¥The $effect in this exercise attempts to create a canvas context, but canvas is undefined. Begin by declaring it at the top level of the component...

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

	let canvas;

	$effect(() => {
		// ...
	});
</script>
<script lang="ts">
	import { paint } from './gradient.js';

	let canvas;

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

...然后将指令添加到 <canvas> 元素:

¥...then add the directive to the <canvas> element:

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

请注意,canvas 的值将保持为 undefined,直到组件安装完毕 - 换句话说,在 $effect 运行之前你无法访问它。

¥Note that the value of canvas will remain undefined until the component has mounted — in other words you can’t access it until the $effect runs.

上一页 下一页
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>