canvas沒有提供繪制虛線的api,我們可以通過moveTo,和lineTo來實現(xiàn)繪制虛線的需求。
思路是將一整條虛線分成若干個小線段,遍歷這些小線段,單數(shù)線段通過lineTo繪制,雙數(shù)線段使用moveTo跳過
具體實現(xiàn)方法如下
const drawDashLine = ([x1, y1], [x2, y2], step = 5) => {
const x = x2 - x1,
y = y2 - y1,
count = Math.floor(Math.sqrt(x * x + y * y) / step),
xv = x / count,
yv = y / count;
ctx.beginPath();
for (let i = 0; i < count; i ++) {
if (i % 2 === 0) {
ctx.moveTo(x1, y1);
} else {
ctx.lineTo(x1, y1);
}
x1 += xv;
y1 += yv;
}
ctx.lineTo(x2, y2);
}
有了繪制虛線的方發(fā),我們便可以輕易的繪制出虛線方框
const drawDashRect = (left, top, width, height, step = 5) => {
drawDashLine([left, top], [left + width, top], step);
ctx.stroke();
drawDashLine([left + width, top], [left + width, top + height], step);
ctx.stroke();
drawDashLine([left + width, top + height], [left, top + height], step);
ctx.stroke();
drawDashLine([left, top + height], [left, top], step);
ctx.stroke();
}
我們知道arc方法不止可以繪制圓,還可以繪制圓弧,所以我們可以繪制多個小圓弧,組成一個虛線圓
const drawDashRound = (x, y, radius, step = 5) => {
const count = Math.floor(360 / step);
step = 5 / 180 * Math.PI * 2;
for (let b = 0, e = step / 2; e <= 360; b += step, e += step) {
ctx.beginPath()
ctx.arc(x, y, radius, b, e);
ctx.stroke();
}
}