知识点
canvas,lineWidth,beginPath,moveTo,lineTo,stroke
canvas官方文档
canvas API中文网 - Canvas API中文文档首页地图
实现的目标
实现从画布A点,到画布B点的连线。连线效果为斑马纹。拐角比例支持自定义,颜色支持自定义。
实现思路
根据拐角比例,获取起始点,终点,拐点的坐标。判断是否处于同一x或者统一y。根据定义的步长,开始循环绘制,从而实现斑马纹的效果。
关键代码
let step = 8;
const x_diff = x1 - x0;
const y_diff = y1 - y0;
const x_index = Math.abs(Math.ceil(x_diff / step));
step = x_diff > 0 ? step : -step;
const y_index = Math.abs(Math.ceil(y_diff / step));
step = y_diff > 0 ? step : -step;
判断向正方向还是反方向绘制
完整版方法(欢迎大家提建议)
const line_color_arr = {
500: ["#DC143C", "#ffffff"],
220: ["#FF1493", "#000000"],
110: ["#8A2BE2", "#000000"],
switch: ["#00FF7F", "#000000"],
distribution_center: ["#FFFF00", "#000000"],
ups: ["#FF4500", "#000000"],
working: ["#00BFFF", "#00BFFF"],
clear: ["rgb(0, 22, 91)", "rgb(0, 22, 91)"]
};
//绘制连线
export function drawLine(
ctx,
x0,
y0,
x1,
y1,
ratio = 0.5,
color_key = "working"
) {
let step = 8;
const x_diff = x1 - x0;
const y_diff = y1 - y0;
let style = true;
const color1 = line_color_arr[color_key][0];
const color2 = line_color_arr[color_key][1];
ctx.lineWidth = 2;
if (y_diff == 0) {
const x_index = Math.abs(Math.ceil(x_diff / step));
step = x_diff > 0 ? step : -step;
for (let i = 0; i < x_index; i++) {
ctx.beginPath();
ctx.moveTo(x0 + step * i, y0);
if (i == x_index - 1) {
ctx.lineTo(x1, y0);
} else {
ctx.lineTo(x0 + step * (i + 1), y0);
}
style = !style;
ctx.strokeStyle = style ? color1 : color2;
ctx.stroke();
}
} else if (x_diff == 0) {
const y_index = Math.abs(Math.ceil(y_diff / step));
step = y_diff > 0 ? step : -step;
for (let i = 0; i < y_index; i++) {
ctx.beginPath();
ctx.moveTo(x0, y0 + step * i);
if (i == y_index - 1) {
ctx.lineTo(x0, y1);
} else {
ctx.lineTo(x0, y0 + step * (i + 1));
}
style = !style;
ctx.strokeStyle = style ? color1 : color2;
ctx.stroke();
}
} else {
const x = Math.round((1 - ratio) * x0 + ratio * x1);
drawLine(ctx, x0, y0, x, y0, undefined, color_key);
drawLine(ctx, x, y1, x1, y1, undefined, color_key);
drawLine(ctx, x, y1, x, y0, undefined, color_key);
}
}
调用方式
drawLine(this.ctx, 30, 40, 80, 90, undefined, "switch");