我正在尝试找到一种方法,可以使用从画布创建的纹理来填充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();
})