调色板是一种经常会遇到的一种东西,常见的调色板有2种,格子调色板和渐变调色板
格子调色板
// 在获取 canvas 对象的前一行,加上下面这行注释,即可获得代码补全
function $$(id) {
return document.getElementById(id)
}
/** @type {HTMLCanvasElement} */
// 获取画布,必须放在获取canvas之前,且中间不可有其他代码
// 1,获取canvas对象
let cnc = $$("canvas")
// 2,获取上下文环境对象context
let cxt = cnc.getContext("2d")
// 3,开始绘制图形
// 调用函数
for (let i = 0; i < 6; i++) {
for (let j = 0; j < 6; j++) {
cxt.fillStyle = "rgb(" + Math.floor(255 - 42.5 * i) + "," + Math.floor(255 - 42.5 * j) + ",0)"
cxt.fillRect(j * 25, i * 25, 25, 25)
}
}
</script>
<canvas id="canvas" width="200" height="200" style="border:1px solid red"></canvas>
效果如下
渐变调色板
<body>
<canvas id="canvas" width="200" height="200" style="border:1px solid red"></canvas>
<script>
// 在获取 canvas 对象的前一行,加上下面这行注释,即可获得代码补全
function $$(id) {
return document.getElementById(id)
}
/** @type {HTMLCanvasElement} */
// 获取画布,必须放在获取canvas之前,且中间不可有其他代码
// 1,获取canvas对象
let cnc = $$("canvas")
// 2,获取上下文环境对象context
let cxt = cnc.getContext("2d")
// 3,开始绘制图形
// 调用函数
let r=255,g=0,b=0;
for (let i = 0; i < 150; i++) {
if(i<25){
g+=10;
}else if(i>25 && i<50){
r-=10;
}else if(i>50 && i<75){
g-=10
b+=10
}else if(i>75 && i<100){
r+=10
}else{
b-=10
}
cxt.fillStyle="rgb(" + r+","+g+","+b+")"
cxt.fillRect(3*i,0,3,cnc.height)
}
</script>
</body>
效果如下