路径填充
我们之前学习的教程主要都以绘制路径和画轮廓线为主,今天我们将学习新的概念:填充路径。
填充路径,填充的必须是路径,所以我们得先有路径才能填充,需要注意,这里的路径不能是一条线段,最少需要两条边的折线。下面我们就以案例的形式学习一下“填充”相关的。
我们先用上一小节学习的 rect
绘制矩形路径然后填充。
先看整体案例:
<!DOCTYPE html>
<html>
<head>
< 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.Style="blue";
ctx.lineWidth=;
ctx.rect(,,,);
ctx.fill(); //直接填充路径
</script>
</body>
</html>
运行结果:
我们从案例中可以看到, fill
,会使用黑色把整个矩形框填满,这样的就是填充。当然,我们也可以利用 fillStyle
设定填充颜色。
fillStyle
的作用是设定填充的颜色,它和设定 Style
描边一样。
先看整体案例:
<!DOCTYPE html>
<html>
<head>
< 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>
运行结果:
我们从案例中可以看到,设定了填充颜色后再 fill
,会使用设定的颜色把整个路径填满。
我们知道, 作用是描边,
fill
作用是填充,我们来整体再回顾学习一下这两个。
先看整体案例:
<!DOCTYPE html>
<html>
<head>
< 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.Style="blue";
ctx.fillStyle="#ccc";
ctx.lineWidth=;
ctx.();
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.Style="blue";
ctx.fillStyle="#ccc";
描边和填充。
:当设定了描边宽度以后,这里先描边后填充和先填充后描边绘制出来的图形是不一样的,后绘制的会覆盖前面绘制的。
ctx.();
ctx.fill();
我们从案例中可以看到,路径的描边和填充在使用上都是相似的。
本小节中我们使用到新的 fill
。
fill()
是用于填充当前已存在的路径的,如果没有设置填充颜色,则认使用黑色填充。
本小节中我们使用到新的 fillStyle
。
fillStyle
用于设置填充的颜色,它和 Style
在使用上是一致的。
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种写法都是的。
本小节我们主要学习了利用 fill
填充图形。