鼠标y轴的位置会改变下一个填充方块的颜色。
当前实例需要学习的函数是colorMode(),其可以改变p5.js解读颜色的方式。默认情况下,fill()、stroke()、background() 及 color() 的参数都是介于 0 至 255 的 RGB 颜色值。这和设置 colorMode(RGB, 255) 的效果一样。
语法:
// 定义全局变量,可以调整barWidth的大小,来看看作品会有什么样的变化?
const barWidth = 20;
let lastBar = -1;
function setup() {
// 画布:720 * 400
createCanvas(720, 400);
// 修改颜色显示模式
colorMode(HSB, height, height, height);
// 无边框+背景黑色
noStroke();
background(0);
}
function draw() {
// 鼠标所在位置(x轴坐标)/块宽度 = 当前在整个画布中的第x块方块,注意强制转换一下,否则下方的条件判断就无效了
let whichBar = int(mouseX / barWidth);
// 判断当前鼠标所在块是不是上一次循环中填色的块
if (whichBar !== lastBar) {
// 获取方块坐标位置,画方块。
let barX = whichBar * barWidth;
// 填充色和鼠标y轴有关。
fill(mouseY, height, height);
rect(barX, 0, barWidth, height);
lastBar = whichBar;
}
}
new p5();