Appearance
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
html,
body {
width: 100vw;
height: 100vh;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
}
</style>
</head>
<body>
<canvas id="canvas"></canvas>
<script>
const canvas = document.querySelector('#canvas')
const context = canvas.getContext('2d')
canvas.style.background = '#ddd'
/**
* setLineDash 在填充线时使用虚线模式。它使用一组值来指定描述模式的线和间隙的交替长度,
* 如果要切换回至实线模式,将 segments 设置为一个空数组即可。
*
* @param {array} segments 一个Array数组。一组描述交替绘制线段和间距(坐标空间单位)
* 长度的数字。 如果数组元素的数量是奇数, 数组的元素会被复制并重复。例如,
* [5, 15, 25] 会变成 [5, 15, 25, 5, 15, 25]。
*/
// 单个虚线的长度为10px 虚线间的间隔为5px
context.setLineDash([10, 5])
// 绘制实线
// context.setLineDash([10, 0])
// 绘制实线
// context.setLineDash([])
context.beginPath()
context.moveTo(10, 10)
context.lineTo(290, 10)
context.stroke()
// 早期没有 setLineDash 这个方法
let y = 15
const drawDashedLine = pattern => {
const context = canvas.getContext('2d')
context.setLineDash(pattern)
context.beginPath()
context.moveTo(10, y)
context.lineTo(290, y)
context.stroke()
y += 20
}
drawDashedLine([1, 1]);
drawDashedLine([10, 10]);
drawDashedLine([20, 5]);
drawDashedLine([15, 3, 3, 3]);
drawDashedLine([20, 3, 3, 3, 3, 3, 3, 3]);
drawDashedLine([12, 3, 3]); // <=> [12, 3, 3, 12, 3, 3]
</script>
</body>
</html>