Reputation: 31
I am working on an app requiring Fabric-js in Svelte. My code is:
<script>
import fabric from "fabric";
let canv = new fabric.Canvas("c");
const rect = new fabric.Rect({
left: 10,
top: 10,
width: 20,
height: 15,
fill: "blue"
});
canv.add(rect);
</script>
<canvas id="c" width="500" height="300" />
but I get an error at the console TypeError: fabric_1.Canvas is not a constructor
. If I however query the fabric object in the console, everything seems fine. Wondering what could be the problem.
Upvotes: 3
Views: 1285
Reputation: 29615
You need to do import { fabric } from 'fabric'
— if you look closely at the object you imported, you'll see that it has a single property named fabric
.
By the time new fabric.Canvas("c")
runs, your canvas element hasn't been created yet. So you need to put it in an onMount
lifecycle callback:
<script>
import { fabric } from "fabric";
import { onMount } from 'svelte';
let canvas;
onMount(() => {
let canv = new fabric.Canvas(canvas);
const rect = new fabric.Rect({
left: 10,
top: 10,
width: 20,
height: 15,
fill: "blue"
});
canv.add(rect);
});
</script>
<canvas bind:this={canvas} width="500" height="300" />
Notice also that I'm using bind:this={canvas}
to assign the DOM element to a local variable, and using that instead of an ID. This is more robust, as it allows you to have multiple instances of the component without the IDs clobbering each other.
Upvotes: 11