来自 Javascript 的 Svelte Mount DOM 元素 [英] Svelte Mount DOM Element from Javascript

查看:30
本文介绍了来自 Javascript 的 Svelte Mount DOM 元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 Svelte 安装 pixi.js 画布,如下所示.app.view 是一个 HTML Canvas 元素,但我不确定如何使用 Svelte 显示它.

<style></style><app.view/>

我暂时只是使用它,但如果能够将它添加到模板中会很棒.

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

解决方案

来自 bind 的文档:这个

<块引用>

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

let 容器;onMount(() => {container.appendChild(app.view);});

这是一个活生生的例子:https://svelte.dev/repl/1184f8491d10a24e68948d7?version=3.12.1"版本=3.12.1

如果您想避免使用包装元素或自己实例化画布,您可以在 onMount 中创建 Pixi 应用程序并将其传递给画布元素:

让视图;让应用程序;onMount(() => {app = new PIXI.Application({看法,//...其他道具});});

另见官方bind:this示例,使用画布.

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);
    })

解决方案

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.

这篇关于来自 Javascript 的 Svelte Mount DOM 元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆