canvas沒(méi)有提供繪制虛線的api,我們可以通過(guò)moveTo哪自,和lineTo來(lái)實(shí)現(xiàn)繪制虛線的需求丛晦。
思路是將一整條虛線分成若干個(gè)小線段,遍歷這些小線段提陶,單數(shù)線段通過(guò)lineTo繪制,雙數(shù)線段使用moveTo跳過(guò)
具體實(shí)現(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方法不止可以繪制圓隙笆,還可以繪制圓弧,所以我們可以繪制多個(gè)小圓弧升筏,組成一個(gè)虛線圓
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();
}
}