路径填充
1. 前言
2. 利用 fill 方法填充路径
2.1 填充矩形
先看整体案例:
<!DOCTYPE html>
<html>
<head>
<Meta charset="utf-8">
<title>网Wiki</title>
<style>
#imooc{
border:px solid #ccc;
}
</style>
</head>
<body>
<canvas id="imooc">您的浏览器不支持 HTML5 canvas 标签</canvas>
<script>
const canvas = document.getElementById('imooc');
const ctx = canvas.getContext('2d');
ctx.strokeStyle="blue";
ctx.linewidth=;
ctx.rect(,,,);
ctx.fill(); //直接填充路径
</script>
</body>
</html>
运行结果:
2.2 设定 fillStyle 属性
先看整体案例:
<!DOCTYPE html>
<html>
<head>
<Meta charset="utf-8">
<title>网Wiki</title>
<style>
#imooc{
border:px solid #ccc;
}
</style>
</head>
<body>
<canvas id="imooc">您的浏览器不支持 HTML5 canvas 标签</canvas>
<script>
const canvas = document.getElementById('imooc');
const ctx = canvas.getContext('2d');
ctx.moveto(,);
ctx.lineto(,);
ctx.lineto(,);
ctx.closePath();
ctx.fillStyle="#cccccc" // 设定填充颜色
ctx.fill();
</script>
</body>
</html>
运行结果:
3. stroke() 和 fill() 对比学习
先看整体案例:
<!DOCTYPE html>
<html>
<head>
<Meta charset="utf-8">
<title>网Wiki</title>
<style>
#imooc{
border:px solid #ccc;
}
</style>
</head>
<body>
<canvas id="imooc">您的浏览器不支持 HTML5 canvas 标签</canvas>
<script>
const canvas = document.getElementById('imooc');
const ctx = canvas.getContext('2d');
ctx.moveto(,);
ctx.lineto(,);
ctx.lineto(,);
ctx.lineto(,);
ctx.closePath();
ctx.strokeStyle="blue";
ctx.fillStyle="#ccc";
ctx.linewidth=;
ctx.stroke();
ctx.fill();
</script>
</body>
</html>
运行结果:
我们将上面案例的绘图内容拆分讲解:
-
获取 canvas 的渲染上下文。
const canvas = document.getElementById('imooc'); const ctx = canvas.getContext('2d');
-
绘制一个图形路径。
ctx.moveto(10,10); ctx.lineto(10,100); ctx.lineto(200,100); ctx.lineto(200,10); ctx.closePath();
-
分别设定描边的颜色和填充的颜色。
ctx.strokeStyle="blue"; ctx.fillStyle="#ccc";
-
描边和填充。
ctx.stroke(); ctx.fill();
我们从案例中可以看到,路径的描边和填充在使用上都是相似的。
4. 方法整理
4.1 fill() 方法
5. 属性整理
5.1 fillStyle 属性
ctx.fillStyle = "blue"
ctx.fillStyle = "#cccccc"
ctx.fillStyle = "#ccc"
ctx.fillStyle = "rgb(200, 200, 200)"
ctx.fillStyle = "rgba(200, 200, 200, 0.5)"
ctx.fillStyle = "hsl(0, 100%, 50%)"
ctx.fillStyle = "hsla(0, 100%, 50%, 0.5)"
上面7种写法都是支持的。