Appearance
实例:直线图形-矩形 案例
矩形同时描边和填充
html
<canvas id="canvas05-01" height="250"></canvas>
js
cxt.strokeStyle = 'red';
cxt.strokeRect(50, 50, 200, 150);
cxt.fillStyle = '#ffe8e8';
cxt.fillRect(50, 50, 200, 150);
效果图:
两个填充矩形的重叠
html
<canvas id="canvas05-02" height="250"></canvas>
js
cxt.fillStyle = 'hotpink';
cxt.fillRect(50, 50, 150, 100);
cxt.fillStyle = 'rgba(0, 0, 255, 0.3)';
cxt.fillRect(100, 100, 150, 100);
效果图:
方格调色板的绘制
需要封装一个方法,传入绘制参数就可以直接绘制
js
createColor(cxt, size, width, height)
参数说明
- cxt是绘制上下文
- size是横向纵向分的个数
- width是整体的宽度
- height是整体的长度
绘制
html
<canvas id="canvas05-03" width="200"></canvas>
js
function createColor(cxt, n, width, height) {
for(let i = 0; i < n; i++) {
for(let j = 0; j < n; j++) {
const degree = (255 / n).toFixed(1);
cxt.fillStyle = `rgba(${Math.floor(255 - degree * i)},${Math.floor(255 - degree * j)},0)`;
const w = Math.floor(width / n);
const h = Math.floor(height / n);
cxt.fillRect(j * w, i * h, w, h);
}
}
}
window.onload = function() {
const cnv = $$('canvas05-03');
const cxt = cnv.getContext('2d');
createColor(cxt, 6, cnv.width, cnv.height)
}
效果图:
渐变调色板的绘制
html
<!-- 宽度是255,根据宽度计算rgb的值即可 -->
<canvas id="canvas05-04" width="255"></canvas>
js
const cnv = $$('canvas05-04');
const cxt = cnv.getContext('2d');
let r = 255;
let g = 0;
let 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, cnv.height);
}
效果图: