我正在 P5.js 中制作像素密度为 1 的草图。该草图的当前状态应该是生成一个 100x100 像素随机亮度的图块(如电缆静态)并在左上方。不过,我创建的平铺图像的像素密度似乎有些问题。每行随机像素之间出现大黑线。
function writeColor(image, x, y, red, green, blue, alpha) {
let index = (x + y * width) * 4;
image.pixels[index] = red;
image.pixels[index + 1] = green;
image.pixels[index + 2] = blue;
image.pixels[index + 3] = alpha;
}
function randomTile(size_x, size_y){
let result = createImage(size_x, size_y);
result.loadPixels();
for (var y = 0; y < size_y; y++){
for (var x= 0; x < size_x; x++){
let brt = floor(random(256));
writeColor(result, x, y, brt, brt, brt, 255);
}
}
result.updatePixels();
return result;
}
function setup() {
createCanvas(600, 400);
pixelDensity(1);
background(0);
let tile = randomTile(100, 100);
image(tile, 0, 0);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.5.0/p5.js"></script>
我试过弄乱像素密度并查找特定于图像的像素密度,但我并没有真正了解这里发生了什么。
如评论中所述,您对图块像素的索引应该相对于该图块的宽度(
size_y
)而不是p5画布width
.
function writeColor(image, x, y, w, red, green, blue, alpha) {
const index = (x + y * w) * 4;
image.pixels[index] = red;
image.pixels[index + 1] = green;
image.pixels[index + 2] = blue;
image.pixels[index + 3] = alpha;
}
function randomTile(sizeX, sizeY) {
const result = createImage(sizeX, sizeY);
result.loadPixels();
for (let y = 0; y < sizeY; y++) {
for (let x = 0; x < sizeX; x++) {
const brt = floor(random(256));
writeColor(result, x, y, sizeY, brt, brt, brt, 255);
}
}
result.updatePixels();
return result;
}
function setup() {
createCanvas(600, 400);
pixelDensity(1);
background(0);
const tile = randomTile(100, 100);
image(tile, 0, 0);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.6.0/p5.js"></script>
无关建议:
camelCase
而不是 snake_case
。const
,而在其他任何地方使用let
。避免var
.