因此,我尝试从 PIXI.js Canvas 中提取像素,并检查了它们,虽然屏幕上的 Canvas 上有图像,但提取的像素完全是黑色的...
然后我进行了调查,这就是我发现的(我需要帮助)
背景信息:
设置:
this.canvas = $('#canvas');
this.canvasDOM = this.canvas[0];
this.renderer = PIXI.autoDetectRenderer(0, 0, {
view: this.canvasDOM,
resolution: 1
});
获取图像:
chooseImage(src) {
const self = this;
const image = new Image();
image.src = src;
image.onload = function() {
const base = new PIXI.BaseTexture(image);
const texture = new PIXI.Texture(base);
const sprite = new PIXI.Sprite(texture);
sprite.position.set(0, 0);
self.currentImage = sprite;
self.render();
};
}
渲染图像:
render() {
if (this.currentImage) {
this.updateDimensions();
const stage = new PIXI.Container();
stage.addChild(this.currentImage);
stage.filters = this.gatherFilters();
const { width, height } = this.currentImage;
stage.filterArea = new PIXI.Rectangle(0, 0, width, height);
this.renderer.render(stage);
}
}
好的,所以你可以忽略渲染函数之前的代码,但特别是渲染函数的倒数第三行是:
this.renderer.render(stage);
现在,这一切都很好!图像弹出, Canvas 上是一只明亮的水母,但有一个小问题:
如果我将其添加到 render() 函数的末尾:
render() {
if (this.currentImage) {
this.updateDimensions();
const stage = new PIXI.Container();
stage.addChild(this.currentImage);
stage.filters = this.gatherFilters();
const { width, height } = this.currentImage;
stage.filterArea = new PIXI.Rectangle(0, 0, width, height);
this.renderer.render(stage);
const actualCanvas = this.renderer.extract.canvas; // the actual canvas on the screen
console.log(actualCanvas.toDataURL());
}
}
它返回一个长字符串,如果替换
console.log(actualCanvas.toDataURL());
带有:(下载库)
download(actualCanvas.toDataURL('image/png'), 'image.png', 'image/png');
它会下载水母图像!
现在,在另一个函数中,我要将图像下载为 png 或 jpg (并且可能的下载类型数组位于另一个类中并动态决定,因此我不能简单地在渲染后缓存像素)
为了向您展示我的问题,我将上面的代码更改为:
setTimeout(() => download(actualCanvas.toDataURL('image/png'), 'image.png', 'image/png'), 1 /* One second delay */);
现在图像是空白的;黑色。,与以前工作时不同
唯一改变的是我添加的延迟。
我进一步检查了这一点,我意识到如果我这样做
setTimeout(() => console.log(this.renderer.extract.pixels()), 1); // extract the pixels after some delay for testing
然后它们就全黑了,但是如果我去掉延迟,它又起作用了
同样,就我而言,由于我自己的原因,我不能简单地缓存图像(不要问)
所以我想知道是否有解决方法,以便在一段延迟后或稍后在提取像素时,像素不仅仅是黑色,并且可以像没有延迟一样工作。
非常感谢任何帮助!
最佳答案
对我来说,这似乎是某种浏览器保护。也许是访问某些资源的非事件驱动代码保护,或者可能是非 https webapps 保护(即使没有证书,您是否也通过 https 尝试过您的应用程序?),或者甚至可能是某种跨域保护(我对此表示怀疑,但是始终出现在待检查列表中)。也许你可以部署一个 fiddle 或类似的东西来测试。希望对您有帮助!
关于javascript - 由于某种原因,PIXI js Canvas 像素保存为黑色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46501558/