gpt4 book ai didi

javascript - 为什么从 Canvas 中检索到的像素都是黑色的?

转载 作者:太空宇宙 更新时间:2023-11-04 11:20:25 25 4
gpt4 key购买 nike

作为练习,我想用随机颜色的像素填充浏览器窗口的背景:https://jsfiddle.net/j8fay7bs/3/

我的问题是如何检索背景图像的当前填充并随机更改像素?目前图像似乎恢复为黑色。

// redraw canvas pixels on resize --------------------------
var render = function resize() {
var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');
context.canvas.width = window.innerWidth;
context.canvas.height = window.innerHeight;
var imageData = context.getImageData(0, 0, canvas.width, canvas.height);

var t0 = performance.now();
for (var i = 0; i < canvas.width*canvas.height; i++) {
if (Math.random() < 0.5) {
imageData.data[i*4] = Math.round(Math.random()*255);
imageData.data[i*4+1] = Math.round(Math.random()*255);
imageData.data[i*4+2] = Math.round(Math.random()*255);
imageData.data[i*4+3] = 255;
}
}
context.putImageData(imageData, 0, 0);
$('#fps').text(1000/(performance.now() - t0) + " fps");
}
window.onresize = render;

// rendering loop ---------------------------------------
(function loop() {
setInterval(render, 10);
})();

最佳答案

您可以在触摸 Canvas 宽度和高度之前检索最后的图像数据,

一旦你触摸它们, Canvas 将被重置:

var render = function resize() {
var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');

var oldImageData = context.getImageData(0, 0, canvas.width, canvas.height); // <----

context.canvas.width = window.innerWidth;
context.canvas.height = window.innerHeight;
var imageData = context.getImageData(0, 0, canvas.width, canvas.height);

updated fiddle

关于javascript - 为什么从 Canvas 中检索到的像素都是黑色的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32831660/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com