canvas蚂蚁线效果代码实例

2018-1-9 23:30| 作者: admin| 查看: 848| 评论: 0|来自: 蚂蚁部落

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

代码实例如下:

[HTML] 纯文本查看 复制代码运行代码
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="author" content="http://www.softwhy.com/" />
<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教程板块。


鲜花

握手

雷人

路过

鸡蛋

最新评论

返回顶部