canvas没有提供绘制虚线的api,我们可以通过moveTo,和lineTo来实现绘制虚线的需求。
思路是将一整条虚线分成若干个小线段,遍历这些小线段,单数线段通过lineTo绘制,双数线段使用moveTo跳过
具体实现方法如下
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);
}
有了绘制虚线的方发,我们便可以轻易的绘制出虚线方框
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();
}
}
网友评论