摘要:在本教程中,您将学习如何使用 Canvas API 绘制线条。
在 JavaScript 中绘制线条的步骤
要在 画布上绘制线条,您可以使用以下步骤:
- 首先,通过调用
beginPath()
方法创建一个新的线条。 - 其次,通过调用
moveTo(x, y)
将绘图光标移动到点(x,y)
,但不绘制线条。 - 最后,通过调用
lineTo(x,y)
方法从前一点绘制到point (x,y)
。
设置线条描边
如果您想使用 strokeStyle
描边线条,您可以在调用 lineTo(x,y)
方法后调用 stroke()
方法。
设置线条宽度
要设置线条宽度,您可以在调用 stroke()
方法之前使用 2D 绘图上下文的 lineWidth
属性。
ctx.lineWidth = 10;
lineTo(x,y) 方法
lineTo(x,y )
方法接受正负参数。
如果 x
为正,则 lineTo(x,y)
方法从起点向右绘制线条。否则,它从起点向左绘制线条。
如果 y
为正,则 lineTo(x,y)
方法从起点沿 y 轴向下绘制线条。否则,它从起点沿 y 轴向上绘制线条。
绘制线条示例
以下显示包含画布元素的 index.html
文件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>JavaScript - Drawing a Line</title>
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<h1>JavaScript - Drawing a Line</h1>
<canvas id="canvas" height="400" width="500">
</canvas>
<script src="js/app.js"></script>
</body>
</html>
Code language: HTML, XML (xml)
此 app.js 包含绘制颜色为红色、宽度为 5 像素的线条,从点 (100, 100) 到 (300, 100)
function draw() {
const canvas = document.querySelector('#canvas');
if (!canvas.getContext) {
return;
}
const ctx = canvas.getContext('2d');
// set line stroke and line width
ctx.strokeStyle = 'red';
ctx.lineWidth = 5;
// draw a red line
ctx.beginPath();
ctx.moveTo(100, 100);
ctx.lineTo(300, 100);
ctx.stroke();
}
draw();
Code language: JavaScript (javascript)
以下显示输出

开发可重用的 drawLine() 函数
以下 drawLine()
函数从一个点绘制到另一个点,并指定描边和宽度
function drawLine(ctx, begin, end, stroke = 'black', width = 1) {
if (stroke) {
ctx.strokeStyle = stroke;
}
if (width) {
ctx.lineWidth = width;
}
ctx.beginPath();
ctx.moveTo(...begin);
ctx.lineTo(...end);
ctx.stroke();
}
Code language: JavaScript (javascript)
要从 (100,100)
绘制到 (100,300)
,线条颜色为绿色,线条宽度为 5 像素,您可以按如下方式调用 drawLine()
函数
const canvas = document.querySelector('#canvas');
if (canvas.getContext) {
const ctx = canvas.getContext('2d');
drawLine(ctx, [100, 100], [100, 300], 'green', 5);
}
Code language: JavaScript (javascript)
总结
- 使用
beginPath()
、moveTo(x, y)
和lineTo(x,y)
绘制线条。 - 使用
strokeStyle
和lineWidth
设置线条描边和线条宽度。
本教程对您有帮助吗?