Canvas 从组件渲染在 Svelte 上不工作
Canvas rendering from component is not working on Svelte
我正在尝试渲染 canvas 并使用 svelte.js 在其上绘制矩形,但如果我在组件端编写渲染代码,它就不起作用。
Here是复制REPL。
如果我将 Canvas.svelte 中的整个代码移动到 app.svelte,它会起作用。
App.svelte:
<script>
import Canvas from './Canvas.svelte';
</script>
<Canvas/>
Canvas.svelte:
<script>
import { onMount } from 'svelte';
let canvasEl;
const canvas = {
width: 1000,
height: 1000
};
const drawRect = (context) => {
context.beginPath();
context.fillStyle = '#000000';
context.rect(0, 0, 40, 10);
context.fill();
};
onMount(() => {
console.log('Onmount');
const context = canvasEl.getContext('2d');
canvas.width = document.body.clientWidth;
canvas.height = document.body.clientHeight;
drawRect(context);
});
</script>
<canvas bind:this={canvasEl} width={canvas.width} height={canvas.height} />
有人知道解决办法吗?
谢谢,
没有找到错误原因,但找到了错误来源:
onMount(() => {
//...
// this 2 lines cause silent error
canvas.width = document.body.clientWidth;
canvas.height = document.body.clientHeight;
//...
});
删除它们,您将看到 canvas 和 rect
我正在尝试渲染 canvas 并使用 svelte.js 在其上绘制矩形,但如果我在组件端编写渲染代码,它就不起作用。
Here是复制REPL。
如果我将 Canvas.svelte 中的整个代码移动到 app.svelte,它会起作用。
App.svelte:
<script>
import Canvas from './Canvas.svelte';
</script>
<Canvas/>
Canvas.svelte:
<script>
import { onMount } from 'svelte';
let canvasEl;
const canvas = {
width: 1000,
height: 1000
};
const drawRect = (context) => {
context.beginPath();
context.fillStyle = '#000000';
context.rect(0, 0, 40, 10);
context.fill();
};
onMount(() => {
console.log('Onmount');
const context = canvasEl.getContext('2d');
canvas.width = document.body.clientWidth;
canvas.height = document.body.clientHeight;
drawRect(context);
});
</script>
<canvas bind:this={canvasEl} width={canvas.width} height={canvas.height} />
有人知道解决办法吗?
谢谢,
没有找到错误原因,但找到了错误来源:
onMount(() => {
//...
// this 2 lines cause silent error
canvas.width = document.body.clientWidth;
canvas.height = document.body.clientHeight;
//...
});
删除它们,您将看到 canvas 和 rect