javascript - p5.j​​s 访问各个像素值

标签 javascript p5.js

我需要访问实时 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.j​​s 访问各个像素值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52262337/

相关文章:

javascript - 具体在 Node.js 中添加浏览器到 POST 请求

javascript - 合并来自两个数组的值

p5.js - p5js sketch 随着时间的推移变慢

javascript - P5中如何给小球添加弹跳压缩动画?

php - Datepicker根据服务器日期/时间获取日期

javascript - codeschool emberjs 7.4 评级产品不工作

javascript - Django ajax 不适用于 jinja2 模板循环内的多个 href

html - Uncaught Error : Can't make callback from given data using MathJax with p5 and html

javascript - 如何在 P5 js 中使用 sin(a) 和距离从 A 调制到 B?

javascript - p5 Canvas 重新居中