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:
<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.
App.svelte
xxxxxxxxxx
55
1
<script>
2
import { onMount } from 'svelte';
3
4
let canvas;
5
6
onMount(() => {
7
const ctx = canvas.getContext('2d');
8
let frame;
9
10
(function loop() {
11
frame = requestAnimationFrame(loop);
12
13
const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
14
15
for (let p = 0; p < imageData.data.length; p += 4) {
16
const i = p / 4;
17
const x = i % canvas.width;
18
const y = i / canvas.height >>> 0;
19
20
const t = window.performance.now();
Console
Cannot read property 'getContext' of undefined
xxxxxxxxxx
82
1
/* App.svelte generated by Svelte v3.23.2 */
2
import {
3
SvelteComponent,
4
attr,
5
detach,
6
element,
7
init,
8
insert,
9
noop,
10
safe_not_equal
11
} from "svelte/internal";
12
13
import { onMount } from "svelte";
14
15
function create_fragment(ctx) {
16
let canvas_1;
xxxxxxxxxx
82
1
/* App.svelte generated by Svelte v3.23.2 */
2
import {
3
SvelteComponent,
4
attr,
5
detach,
6
element,
7
init,
8
insert,
9
noop,
10
safe_not_equal
11
} from "svelte/internal";
12
13
import { onMount } from "svelte";
14
15
function create_fragment(ctx) {
16
let canvas_1;
Compiler options
result = svelte.compile(source, {
generate:
});xxxxxxxxxx
1
1
canvas.svelte-7wnteg{width:100%;height:100%;background-color:#666;-webkit-mask:url(svelte-logo-mask.svg) 50% 50% no-repeat;mask:url(svelte-logo-mask.svg) 50% 50% no-repeat}
xxxxxxxxxx
1
1
canvas.svelte-7wnteg{width:100%;height:100%;background-color:#666;-webkit-mask:url(svelte-logo-mask.svg) 50% 50% no-repeat;mask:url(svelte-logo-mask.svg) 50% 50% no-repeat}