绘制线段
1. 前言
线段的绘制在 canvas 里应该是最基础的一个操作,很多复杂的图案就是由最简单的线段组成的,所以我们的课程就从绘制线段开始。
2. 绘制线段
开始之前,我先拿现实生活中画一条线段的流程来类比我们在 canvas 中绘制线段。
在现实中,我们如何去画一条线段呢?我们暂且就按下面的流程来做一遍:
- 拿到一张白纸(画布);
- 铅笔移动到起点;
- 开始描线到终点(类似于素描中的打线);
- 选择一种有颜色的画笔;
- 开始描边(画出轮廓线)。
在 canvas 中,我们也是按这个流程来绘制一条线段的。
先看整体案例:
<!DOCTYPE html>
<html>
<head>
<Meta charset="utf-8">
<title>网Wiki</title>
<style>
#imooc{
border:px solid #ccc;
}
</style>
</head>
<body>
<canvas id="imooc"></canvas>
<script>
// 拿到一张白纸
const canvas = document.getElementById('imooc');
const ctx = canvas.getContext('2d');
// 打线笔移动到起点
ctx.moveto(,);
// 开始描线到终点
ctx.lineto(,);
// 选择绿色的画笔
ctx.strokeStyle="green";
// 开始用画笔描边
ctx.stroke();
</script>
</body>
</html>
运行结果:
我们将上面的例子类比现实中画线的流程拆分讲解:
-
拿到一张白纸类比我们获取到 canvas 的渲染上下文。
const canvas = document.getElementById('imooc'); const ctx = canvas.getContext('2d');
-
我们开始铅笔打线,先把铅笔移动到 (100,100) 这个点,这里使用的方法是:
moveto(x,y)
,参数为起点坐标。ctx.moveto(100, 100)
-
我们用铅笔从起点画一个路径到终点,也就是 (200,300) 这个点,这里使用的方法是:
lineto(x, y)
,参数为终点坐标。ctx.lineto(200,300)
-
选择一个画笔,这里我们设定为绿色的画笔,这是使用了
strokeStyle
属性,这里需要注意属性和方法的区别,直观的理解就是:属性是一个变量,方法是一个函数。ctx.strokeStyle = "green"
-
开始用画笔描边,这里使用的方法是:
stroke()
,这个方法没有参数。ctx.stroke()
到这里,我们就完成了一条线段的绘制。
3. 线段方法整理
本小节中我们使用到了三个方法,都是和绘制线段相关的。
3.1 moveto(x, y)
参数说明:
3.2 lineto(x, y)
参数说明:
3.3 stroke()
4. 线段属性整理
4.1 strokeStyle
ctx.strokeStyle = "blue"
ctx.strokeStyle = "#cccccc"
ctx.strokeStyle = "#ccc"
ctx.strokeStyle = "rgb(200, 200, 200)"
ctx.strokeStyle = "rgba(200, 200, 200, 0.5)"
ctx.strokeStyle = "hsl(0, 100%, 50%)"
ctx.strokeStyle = "hsla(0, 100%, 50%, 0.5)"
以上 7 种设定描边颜色的写法都是支持的。