Pixi js如何使用画布上的纹理来填充形状

3

我正在尝试找到一种方法,可以使用从画布创建的纹理来填充PIXI.js中的形状。这样做的原因是我想在普通的HTML画布上创建渐变,然后将其制作成纹理并添加到PIXI舞台中。现在我已经可以做到这一点了,这是我测试的第一件事,它有效。但最终目标是使用Graphics类在PIXI.js中创建形状,然后用我的渐变填充它们。我不知道如何实现这一点,因为.beginFill()方法只接受颜色。我该如何用纹理来填充形状呢?以下是我的代码。我知道辅助画布的创建有点冗长,但那是以后的问题。

$(document).ready(function() {
    var stage = new PIXI.Container();
    var renderer = PIXI.autoDetectRenderer(800, 600);
    document.body.appendChild(renderer.view);

    //Aliases
    var Sprite = PIXI.Sprite;
    var TextureCache = PIXI.utils.TextureCache;
    var resources = PIXI. loader.resources;

    function AuxCanvas(id, w, h, color1, color2) {
        this.id = id;
        this.w = w;
        this.h = h;
        this.color1 = color1;
        this.color2 = color2;
    }
    // create and append the canvas to body
    AuxCanvas.prototype.create = function() {
        $('body').append('<canvas id="'+
            this.id+'"  width="'+
            this.w+'" height="'+
            this.h+'"></canvas>');
    }
    // draw gradient
    AuxCanvas.prototype.drawGradient = function() {
        var canvas = document.getElementById(this.id);
        var ctx = canvas.getContext('2d');
        var gradient = ctx.createLinearGradient(0, 0, 800, 0);
        gradient.addColorStop(0, this.color1);
        gradient.addColorStop(1, this.color2);
        ctx.fillStyle = gradient;
        ctx.fillRect(0, 0, this.w, this.h);
    }

    function setup() {

        var graphics = new PIXI.Graphics();
        graphics.beginFill(PIXI.Texture.fromCanvas(can1)); //This doesn't work obviously
        graphics.drawCircle(60, 185, 40); 
        graphics.endFill();
        stage.addChild(graphics);
        renderer.render(stage);
    }

    var can1 = new AuxCanvas("can1", 800, 600, "green", "yellow");
    can1.create();
    can1.drawGradient();

    var can2 = new AuxCanvas("can2", 800, 600, "blue", "red");
    can2.create();
    can2.drawGradient();

    setup();
})
1个回答

10

好的,我想出了一种方法,其实很简单。 只需将 Graphics 对象作为从 HTML 画布创建的精灵的蒙版即可。

function setup() {
    var can2 = document.getElementById('can2');
    var sprite = new Sprite(PIXI.Texture.fromCanvas(can2))
    var graphics = new PIXI.Graphics();
    graphics.beginFill();
    graphics.drawCircle(300, 300, 200); 
    graphics.endFill();
    sprite.mask = graphics;
    stage.addChild(sprite);
    renderer.render(stage);
}

此外,将图形附加为精灵的子元素是最好的方法,只需要确保它们具有相同的尺寸。完成这一步后,我可以自由移动精灵,其渐变纹理不会改变,或者更准确地说,它随着精灵移动。当然,所有要素的尺寸都必须相等。

var graphics = new PIXI.Graphics();
    graphics.beginFill();
    graphics.drawCircle(100, 100, 100); 
    graphics.endFill();
    sprite.addChild(graphics);
    sprite.mask = graphics;

1
这真是太棒了,而且看起来它也可以与LottieJS一起使用。https://airbnb.io/lottie/ 语法稍作更新,您需要lottie渲染器来使用画布,并调用纹理的更新以获取最新的动画帧。var anim = document.getElementById('lottieCanvas'); if(anim){ this.texture = PIXI.Texture.from(anim); this.texture.update(); } - Borg

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接