Fabric.js / Svelte 中的 fabricjs,有什么解决方法吗?

Fabric.js / fabricjs in Svelte, is there any workaround?

我已经在 REPL 中尝试过这段代码,但找不到任何可用的示例。我正在尝试使用织物铅笔刷在 canvas 上自由绘图,但是,这只是一个矩形:

<script>

    const fabric = () => {
        fabric = new window.fabric();
    }
    
    function drawMD(){
        let canvas = new fabric.Canvas('c')
        let rect =  new fabric.Rect({
            left:150, top, 150, fill: 'red, width: 200, height: 200, angle: 45
        })
        
        canvas.add(rect)
    }
</script>

<svelte:head>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/500/fabric.min.js" on:load={fabric}></script>
</svelte:head>

<div className="MarkdownEditor">
    <canvas id="c" width="600" height="600" style="border:1px solid #000000;" on:click={drawMD}>
</canvas>
</div>

您不需要 window 部分,Rect 对象中有一些拼写错误,className 在 Svelte 中不起作用。如果你想直接绘制而不用点击canvas,你可以在onMount里面这样做。这是一个有效的 REPL
(打开 REPL 时可能会出现错误fabric is not defined - 只需将 <svelte:head> 向下移动一行,然后就可以了...)

<svelte:head>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/500/fabric.min.js"></script>
</svelte:head>

<script>
    import {onMount} from 'svelte'

    onMount(() => {
        let canvas = new fabric.Canvas('c2')
        let rect =  new fabric.Rect({
            left:120, top: 10, fill: 'teal', width: 150, height: 150, angle: 45
        })        
        canvas.add(rect)
    })

    function drawMD(){
        let canvas = new fabric.Canvas('c')
        let rect =  new fabric.Rect({
            left:120, top: 10, fill: 'red', width: 150, height: 150, angle: 45
        })        
        canvas.add(rect)
    }
</script>

<div class="MarkdownEditor">
    <canvas id="c" width="250" height="250" style="border:1px solid #000000;" on:click={drawMD}></canvas>
</div>

<canvas id="c2" width="250" height="250" style="border:1px solid #000000;"></canvas>