来自 Javascript 的 Svelte Mount DOM 元素

2024-01-04

我正在尝试安装一个pixi.js画布与 Svelte 如下所示。app.view is an HTML Canvas元素,但我不知道如何用 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 />

我暂时只是使用它,但如果能够将其添加到模板中那就太好了。

    onMount(() => {
        document.body.appendChild(app.view);
    })

从文档bind:this https://svelte.dev/docs#bind_element

要获取对 DOM 节点的引用,请使用bind:this.

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

这是一个活生生的例子:https://svelte.dev/repl/118b7d4540c64f8491d10a24e68948d7?version=3.12.1 https://svelte.dev/repl/118b7d4540c64f8491d10a24e68948d7?version=3.12.1

如果您想避免包装元素或自己实例化画布,您可以在以下位置创建 Pixi 应用程序onMount并向其传递一个画布元素:

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

也可以看看官方bind:this example https://svelte.dev/examples#bind-this使用画布。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

来自 Javascript 的 Svelte Mount DOM 元素 的相关文章

随机推荐