gpt4 book ai didi

javascript - updatePixels() 实际上并未更新像素

转载 作者:行者123 更新时间:2023-12-01 01:13:39 28 4
gpt4 key购买 nike

我正在尝试制作一个程序,它接受一个字符串,将其转换为 base64,然后转换为二进制。然后,它获取二进制并将像素更改为黑色像素为 0,白色像素为 1。

我已经将像素数组更改为我想要的内容,但当我调用 updatePixels() 时,它实际上并没有发生变化。

我的目标是获取 Canvas 并将其导出为图像。

我的草图:

let hw;
let input, button;
let binaryOut;

function setup() {
createCanvas(140,140);
input=createInput();
pixelDensity(1);

button = createButton("get image");
button.mousePressed(txtTo64ToBin)

loadPixels();
}

function txtTo64ToBin(){
str = input.value();
str = btoa(str);
let output = '';
str = str.split("")
for(let i=0;i<str.length;i++){
let base = str[i].charCodeAt(0).toString(2)
while(base.length < 8){
base = "0"+base;
}
output += base;
}
binaryOut = output;
console.log(binaryOut)
updateImage(binaryOut.split(''))
}

function updateImage(binArr){
hw = factors(binArr.length);
hw = hw[hw.length-1];
console.log(hw);
resizeCanvas(...hw,false)
pixels = []
for(let i=0; i<binArr.length; i++){
pixels[i*4] = map(binArr[i],0,1,0,255);
pixels[i*4+1] = map(binArr[i],0,1,0,255);
pixels[i*4+2] = map(binArr[i],0,1,0,255);
pixels[i*4+3] = 255;
}
console.log(pixels)
updatePixels() //here is the updatePixels function call
}

function draw() {
noLoop();

}

function factors(num) {

var half = Math.floor(num / 2),
arr = [],
i, j;


num % 2 === 0 ? (i = 2, j = 1) : (i = 3, j = 2);

for (i; i <= half; i += j) {
if(num % i === 0 && i <= num/i){
arr.push([i,num/i]);
}
}
return arr;
}

我很困惑,非常感谢任何帮助。

最佳答案

请尝试break your problem down into smaller steps并将问题隔离在一个较小的示例中。

这是一个显示相同问题的示例草图:


let button;

function setup() {
createCanvas(140,140);

button = createButton("test");
button.mousePressed(updateImage);

loadPixels();
}

function updateImage(){
pixels = [];
for(let i=0; i < width * height; i++){
pixels[i*4] = 255;
pixels[i*4+1] = 0;
pixels[i*4+2] = 0;
pixels[i*4+3] = 255;
}
updatePixels();
}

function draw() {
noLoop();
}

我们可能期望当我们单击按钮时 Canvas 会变成红色,但事实并非如此。看看这个例子如何更容易使用,因为我们不必考虑您的任何逻辑?

无论如何,问题是由这一行引起的:

 pixels = [];

去掉该行,示例程序就可以运行。

我猜测这是因为 pixels 不是一个标准的 JavaScript 数组。来自 the reference :

Uint8ClampedArray containing the values for all the pixels in the display window.

...

Note that this is not a standard javascript array.

关于javascript - updatePixels() 实际上并未更新像素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54948086/

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