2

I'm trying to mount a pixi.js canvas with Svelte like below. app.view is an HTML Canvas element but I'm not sure how to display it with Svelte.

<script>
    import * as PIXI from 'pixi.js'
    import { onMount } from 'svelte';
    let app = new PIXI.Application({ 
        width: 256,         // default: 800
        height: 256,        // default: 600
        antialias: true,    // default: false
        transparent: false, // default: false
        resolution: 1       // default: 1
    })
</script>

<style></style>

<app.view />

I'm just using this for the time being but it would be great to be able to add it to the template.

    onMount(() => {
        document.body.appendChild(app.view);
    })
Ryan King
  • 3,538
  • 12
  • 48
  • 72

1 Answers1

5

From the docs of bind:this

To get a reference to a DOM node, use bind:this.

<div bind:this={container}/>
let container;
onMount(() => {
  container.appendChild(app.view);
});

Here's a live example: https://svelte.dev/repl/118b7d4540c64f8491d10a24e68948d7?version=3.12.1

If you want to avoid the wrapper element or instantiate the canvas yourself, you could create the Pixi app in onMount and pass it a canvas element:

<canvas bind:this={view}/>
let view;
let app;
onMount(() => {
  app = new PIXI.Application({
    view,
    // ...other props
  });
});

See also the official bind:this example that uses a canvas.