我试图想出一种方法,我可以使用从画布创建的纹理填充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();
})
答案 0 :(得分:4)
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;