I wanted to add a simple SVG example that is manipulatable with SVG.js
I tried this.
<main>
<section class="center">
<h1>Hello!</h1>
<p>This is project page.</p>
</section>
<section id="canvas">
<canvas></canvas>
</section>
</main>
<script>
import { SVG } from '@svgdotjs/svg.js';
var draw = SVG().addTo("#canvas").size(300, 300)
var rect = draw.rect(100, 100).attr({ fill: '#f06' })
</script>
but it prints out this error on browser console:
TypeError: Cannot read properties of null (reading 'put')
at Svg.addTo (@svgdotjs_svg__js.js?t=1722923695034&v=5d11dd42:1846:32)
at instance (index.svelte:13:22)
at init (chunk-5CD65IUO.js?v=5d11dd42:2137:23)
at new Project (index.svelte:14:55)
at createComponent (svelte-hooks.js?v=5d11dd42:206:20)
at targetCmp.$replace (svelte-hooks.js?v=5d11dd42:269:15)
at refreshComponent (proxy.js?v=5d11dd42:171:15)
at ProxyAdapterDom.rerender (proxy-adapter-dom.js?v=5d11dd42:77:5)
at proxy.js?v=5d11dd42:408:9
at Array.forEach (<anonymous>)
It seemed that Svg.addTo() method cannot find the targetDOM.
I thouth it was the problem of DOM load timing, so I tried this:
<main>
<section class="center">
<h1>Hello!</h1>
<p>This is project page.</p>
</section>
<section id="canvas">
<canvas></canvas>
</section>
</main>
<script>
import { SVG } from '@svgdotjs/svg.js';
document.addEventListener("DOMContentLoaded",()=>{
var draw = SVG().addTo("#canvas").size(300, 300)
var rect = draw.rect(100, 100).attr({ fill: '#f06' })
});
</script>
And… nothing happens. No errors, no logs. Seems like ‘DOMContentLoaded’ event is never fired in svelte? Can anyone help me implementing SVG.js on vite+svelte app?
2
Answers
Resolved it:
Svelte has different lifecyle.
onMount
function does the job of I want.It’s better to use your own action than to use
onMount()
: