demo.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<canvas id="cvs"></canvas>
<script>
var cvs = document.getElementById('cvs');
var ctx = cvs.getContext('2d');
/*
* 设置画线的时候空白部分和实线部分的大小。
* ctx.setLineDash( [ 5, 3, 2] )
* */
/*
* 设置虚线绘制时的偏移量
* ctx.lineDashOffset = 3;
* */
ctx.lineDashOffset = 3; //设置虚线的偏移量(线不偏移,只是虚的位置偏移)
ctx.setLineDash( [ 5, 4, 3] ); //实线部分和白线部分的大小依次是5,4,3,5,4,3...
ctx.moveTo( 10, 10 );
ctx.lineTo( 310, 10 );
ctx.stroke();
/*
* 获取线条绘制规则。
* ctx.getLineDash()
* */
console.log(ctx.getLineDash()); //数组,长度是偶数(如果是奇数会乘2变成偶数)
</script>
</body>
</html>