我想使用 Canvas 制作一个简单的火焰效果。目前我不了解在此上下文中使用双缓冲区的编码方面(错误)。我使用 Brackets 编写了代码,JSLint 代码通过了。错误是“无法设置未定义的属性‘NaN’。” 在这个例子中我做错了什么?
/*global document: false */
/*global setInterval */
function getPixel(imageData, x, y) {
"use strict";
var index = 0, r, g, b;
index = (x + y * imageData.width) * 4;
r = imageData.data[index];
g = imageData.data[index + 1];
b = imageData.data[index + 2];
return [r, g, b];
}
function setPixel(imageData, x, y, r, g, b, a) {
"use strict";
var index = 0;
index = (x + y * imageData.width) * 4;
imageData.data[index] = r;
imageData.data[index + 1] = g;
imageData.data[index + 2] = b;
imageData.data[index + 3] = a;
}
var element = document.getElementById("canvas");
var c = element.getContext("2d");
var w = element.width;
var h = element.height;
// set buffer
var offScreenCanvas = document.createElement('canvas');
offScreenCanvas.width = w;
offScreenCanvas.height = h;
var ctxOffscreen = offScreenCanvas.getContext('2d');
function init() {
"use strict";
var x, y, i, j, r, g, b;
for (j = 0; j < 10; j += 1) {
for (i = 0; i < 800; i += 1) {
x = i;
y = j;
r = 255 - Math.round(Math.random() * 50);
g = 0;
b = 0;
setPixel(ctxOffscreen, x, y, r, g, b, 255);
}
}
c.putImageData(ctxOffscreen, 0, 0);
}
function animation() {
"use strict";
var a1, a2, a3, a4, r, g, b, i, j;
// draw
for (j = 9; j < 100; j += 1) {
for (i = 0; i < 800; i += 1) {
a1 = getPixel(offScreenCanvas, i, j - 1);
a2 = getPixel(offScreenCanvas, i, j + 1);
a3 = getPixel(offScreenCanvas, i - 1, j);
a4 = getPixel(offScreenCanvas, i + 1, j);
r = Math.round((a1[0] + a2[0] + a3[0] + a4[0]) / 4);
g = Math.round((a1[1] + a2[1] + a3[1] + a4[1]) / 4);
b = Math.round((a1[2] + a2[2] + a3[2] + a4[2]) / 4);
setPixel(offScreenCanvas, i, j, r, g, b, 255);
}
}
// copy buffer onto the canvas
c.putImageData(offScreenCanvas, 0, 0);
}
init();
setInterval(animation, 20);
错误在 setPixel 定义中。
imageData.data[index] = r;