p5.js入门学习-function

114 阅读1分钟

function是定义函数的关键词,以下示例我们定义了一个drawTarget函数,只需要在draw函数中调用该函数,就可以实现相应图形的绘制。

可以减少重复代码的编写,提高编程效率与程序运行效率。

image.png

function setup() {
  createCanvas(720, 400);
  background(51);
  noStroke();
  noLoop();
}
// 在画面中
function draw() {
  // 第1次调用函数
  drawTarget(width * 0.25, height * 0.4, 200, 4);
  // 第2次调用函数
  drawTarget(width * 0.5, height * 0.5, 300, 10);
  // 第3次调用函数
  drawTarget(width * 0.75, height * 0.3, 120, 6);
}
// 函数:drawTarget(xloc, yloc, size, num);
// xloc、yloc为图形的坐标,size为整个图形的尺寸,num代表需要绘制多少个圆环。
function drawTarget(xloc, yloc, size, num) {
  // 计算圆环的灰度值,与下列循环中计算各圆环填充色算法配合使用。
  const grayvalues = 255 / num;
  // 计算圆环的尺寸
  const steps = size / num;
  for (let i = 0; i < num; i++) {
    // 设置圆环填充色
    fill(i * grayvalues);
    // 使用椭圆绘图工具
    ellipse(xloc, yloc, size - i * steps, size - i * steps);
  }
}
new p5();

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