Pixi js 使用来自 canvas 的纹理填充形状

Pixi js fill shape with a texture from canvas

我正在尝试找出一种方法,我可以使用从 canvas 创建的纹理填充 PIXI.js 中的形状。 这样做的原因是我希望能够在正常的 html canvas 上创建渐变,然后他们用它制作纹理并将其添加到 pixi 舞台。现在我可以做到了,这是我测试的第一件事,它有效。但最终目标是使用图形 class 在 PIXI.js 中创建形状,然后用我的渐变填充它们。我不知道如何完成此操作,因为 .beginFill() 方法只接受一种颜色。如何用纹理填充形状? 这是我的代码。我知道辅助 canvas 创建有点冗长,但这是以后的问题。

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

好吧,我想出了一个办法,其实很简单。 只需将 Graphics 对象设为从 html canvas.

创建的精灵的遮罩
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;