如何使用Phaser 3绘制画布元素?

时间:2019-03-02 23:52:50

标签: javascript phaser-framework

我正在使用Phaser 3 JavaScript图形库:https://phaser.io/phaser3

我在库外有一个先前创建的canvas元素。现在,我想使用Phaser 3在屏幕上绘制此画布元素。作为一个玩具示例,请考虑以下代码:

const game = new Phaser.Game({
    type: Phaser.AUTO,
    width: 1000,
    height: 1000,
    scene: {
        create,
    },
});

function create() {
    // Create a circle
    // From: https://www.w3schools.com/tags/canvas_arc.asp
    const circle = document.createElement('canvas');
    const ctx = circle.getContext('2d');
    ctx.beginPath();
    ctx.arc(100, 75, 50, 0, 2 * Math.PI);
    ctx.stroke();

    // Draw the circle using Phaser 3
    const circleTexture = this.textures.createCanvas('circle');
    circleTexture.setDataSource(circle);
    circleTexture.refresh();
    const circleImage = this.add.image(150, 200, 'circle');
}

运行时,此代码不会在屏幕上绘制任何内容。完成这项任务的正确方法是什么?

1 个答案:

答案 0 :(得分:0)

答案是这样的

this.textures.addCanvas('circle', circle);

因此,完整的工作代码如下:

const game = new Phaser.Game({
    type: Phaser.AUTO,
    width: 1000,
    height: 1000,
    scene: {
        create,
    },
});

function create() {
    // Create a circle
    // From: https://www.w3schools.com/tags/canvas_arc.asp
    const circle = document.createElement('canvas');
    const ctx = circle.getContext('2d');
    ctx.beginPath();
    ctx.arc(100, 75, 50, 0, 2 * Math.PI);
    ctx.stroke();

    // Draw the circle using Phaser 3
    this.textures.addCanvas('circle', circle);
    const circleImage = this.add.image(150, 200, 'circle');
}
相关问题