您需要使用异步“循环”,以便您可以更新s像素,让显示更新结果,然后继续。
JavaScript是单线程的,所以在当前循环完成时没有任何更新,因为线程已被占用。
看着油漆变干
这里有一个方法,你可以使用。您可以定义要反转(1是有效的,如果你想看到的每个像素的像素数的“批”的大小,但是这可能需要很长的时间:如果你要显示的每个单一
ie. 16.67ms x total number of pixels.
所以具有640x400的图像(如在下面的演示)像素更新然后它将采取:
640 x 400 x 16.67ms = 4,267,520 ms, or more than an hour
东西有记(显示不能更新大于每16.67毫秒= 60帧速度更快)下面我们用128。像素每批
实例
请注意,批量值必须与图像的宽度相匹配。 F.ex.如果您的图像宽度为640像素,则可以使用1,5,10,20,... 64,128等。
如果您希望宽度不一定除1或小数值之外的任何值,则必须执行一个简单的计算来限制最后一批的一行为getImageData()需要参数来定义图像内的区域。或者,只是一行一行......
你也可以使用“批”的垂直瓷砖值(在这种情况下,框可能是一个更好的术语)。
var img = new Image();
img.crossOrigin = "";
img.onload = painter;
img.src = "http://i.imgur.com/Hl3I0cx.jpg";
function painter() {
// setup canvas and image
var canvas = document.querySelector("canvas"),
ctx = canvas.getContext("2d");
// set canvas size = image size
canvas.width = this.naturalWidth; canvas.height = this.naturalHeight;
// draw in image
ctx.drawImage(this, 0, 0);
// prepare loop
var batch = 128,
x = 0, y = 0,
w = canvas.width - batch,
h = canvas.height;
(function asyncUpdate() {
// do one batch only
var idata = ctx.getImageData(x, y, batch, 1), // get a bacth of pixels
data = idata.data,
i = 0, len = data.length;
while(i < len) { // invert the batch
data[i] = 255 - data[i++];
data[i] = 255 - data[i++];
data[i] = 255 - data[i++];
i++
}
ctx.putImageData(idata, x, y); // update bitmap
x += batch;
if (x > w) { // check x pos
x = 0;
y++;
}
if (y < h) { // new batch?
requestAnimationFrame(asyncUpdate); // let display update before next
}
else {
// use a callback here...
console.log("Done");
}
})();
}