我正在尝试创建一个带字符串的程序,将其转换为base64,然后转换为二进制。然后它采用二进制并将像素更改为0的黑色像素和1的白色像素。
我已经让像素阵列改变为我想要的,但是当我调用updatePixels()
时它实际上并没有改变。
我的目标是然后将画布并将其导出为图像。
我的素描:
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();
}
我们可能希望在单击按钮时将画布变为红色,但事实并非如此。看看这个例子如何更容易使用,因为我们不必考虑你的任何逻辑?
无论如何,这个问题是由这条线引起的:
pixels = [];
拿出那条线,示例程序可以工作。
我的猜测是因为pixels
不是标准的JavaScript数组。来自the reference:
Uint8ClampedArray包含显示窗口中所有像素的值。
...
请注意,这不是标准的javascript数组。