p5.js入门学习-创建图像

121 阅读1分钟

createImage() 函数能让我们巧妙地操控一个像素缓冲区。 此示例创建了一个渐变图像。

let img;
function setup() {
  // 画布:720 * 400
  createCanvas(720, 400);
  // 创建图像:230x230
  img = createImage(230, 230);
  // createImage创建了一个原始图像,但是图像内并没有内容
  // 可以通过loadPixels函数,读取/修改图像中每一个像素点的值
  img.loadPixels();
  // 图像实际上就是一个二维数组,我们通过嵌套循环的方式遍历图像中的每一个像素点。
  for (let x = 0; x < img.width; x++) {
    for (let y = 0; y < img.height; y++) {
      // 根据图像高度,取一个合适的值,作为图像的透明度值
      let a = map(y, 0, img.height, 255, 0);
      // 使用 set() 设置该位置像素的颜色
      img.set(x, y, [0, 153, 204, a]);
    }
  }
  // 使用 set() 后,必须调用updatePixels() 以使改变生效
  img.updatePixels();
}
function draw() {
  background(0);
  // 固定位置的图像
  image(img, 90, 80);
  // 跟随鼠标移动的图像,可以思考一下为什么不是image(img, mouseX , mouseY );
  image(img, mouseX - img.width / 2, mouseY - img.height / 2);
}
new p5();

p5js 开源社区 - 乐述云享 (aleshu.com)