通过Canvas实现斑马纹连线

知识点

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");

实际效果

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值