canvas蚂蚁线效果代码实例

快乐打工仔 分类:实例代码

canvas蚂蚁线效果代码实例属于前端实例代码,有关更多实例代码大家可以查看

分享一段代码实例,它利用canvas实现了蚂蚁线效果。

代码实例如下:

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="author" content="http://www.pipipi.net/" />
<title>犀牛前端部落</title>
<style>
canvas {
  width: 500px;
  height: 200px;
}
</style>
<script>
window.onload = function () {
  const canvas = document.getElementsByTagName('canvas')[0];
  const ctx = canvas.getContext('2d');
  let options = {
    split: 10,
    length: 15,
    y: 50,
    lineColor: "#FF6F00",
    maxLength: 100,
    margin: 20,
    fontSize: 12,
    text: "犀牛前端部落"
  }
  startDraw(options);
  
  function startDraw(s) {
    s.canvasWidth = canvas.width;
    var textOptions = {
      text: s.text,
      fontSize: s.fontSize,
      fontFamily: s.fontFamily
    }
    ctx.font = s.fontSize + "px " + s.fontFamily;
    var textWidth = ctx.measureText(s.text).width;
    var textX = (s.canvasWidth - textWidth) / 2;
    ctx.fillText(s.text, textX, s.y + s.fontSize / 2);

    var lineTo = {
      y: s.y,
      lineColor: s.lineColor,
      split: s.split,
      length: s.length,
      maxLength: s.maxLength,
    }
    var lineToL = {
      x: textX - s.margin,
      startX: textX - s.margin,
      direction: -1
    }
    Object.assign(lineToL, lineTo);
    drawRowLine(lineToL);
    var lineToR = {
      x: textX + textWidth + s.margin,
      startX: textX + textWidth + s.margin,
      direction: 1
    }
    Object.assign(lineToR, lineTo);
    drawRowLine(lineToR);
  }

  function drawRowLine(s) {
    ctx.moveTo(s.x, s.y);
    s.x = s.x + s.length * s.direction;
    ctx.lineTo(s.x, s.y);
    ctx.strokeStyle = s.lineColor;
    ctx.stroke();
    s.x = s.x + s.split * s.direction;
    if (Math.abs(s.startX - s.x) < s.maxLength) {
      drawRowLine(s);
    }
  }
}
</script>
</head>
<body>
<canvas></canvas>
</body>
</html>

实现了简单的绘制蚂蚁线的效果,比较简单。

更多canvas内容可以参阅 canvas教程 板块。

canvas蚂蚁线效果代码实例,这样的场景在实际项目中还是用的比较多的,关于canvas蚂蚁线效果代码实例就介绍到这了。

回复

我来回复
  • 暂无回复内容