我需要访问实时 Canvas 的各个像素值,该 Canvas 具有从用户输入中绘制的图案(形状)。
像下面这样,
function draw(){
stroke(255);
if (mouseIsPressed == true) {
if(mouseX != old_mX || mouseY != old_mY)
{
obstacle[obstacle.length] = [mouseX, mouseY];
//line(mouseX, mouseY, pmouseX, pmouseY);
old_mX = mouseX;
old_mY = mouseY;
}
}
fill(255);
beginShape();
for(i = 0; i < obstacle.length;i++){
vertex(obstacle[i][0],obstacle[i][1]);
}
endShape();
}
绘制完成后需要访问各个像素值
function keyTyped() {
if ( key == 'n')
{
obstacle = []
}
if( key == 'd'){
loadPixels();
//rest of the action
updatePixels();
}}
问题是 loadPixels();不加载具有正确值的数组,加载的数组更像是包含随机模式的随机数组
是否有正确的方法来访问像素?
最佳答案
我尝试了你的代码,看起来它正常地将像素加载到 pixels[]
中。我认为问题可能在于你对“正常”的期望。
根据https://p5js.org/reference/#/p5/pixels :
The first four values (indices 0-3) in the array will be the R, G, B, A values of the pixel at (0, 0). The second four values (indices 4-7) will contain the R, G, B, A values of the pixel at (1, 0).
因此,如果您在全黑 Canvas 上运行 loadPixels()
,您将获得以下数组:
console.log(pixels);
-> [0, 0, 0, 255, 0, 0, 0, 255, 0, 0, 0, 255...]
第一个像素中 0 红色、0 绿色、0 蓝色、255 alpha,然后
第二个像素中 0 红色、0 绿色、0 蓝色、255 alpha,然后...
Alpha 是衡量像素透明度的指标。 255表示完全不透明,0表示完全透明。
关于javascript - p5.js 访问各个像素值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52262337/