canvas螞蟻線效果程式碼例項

admin發表於2018-01-09

分享一段程式碼例項,它利用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教程板塊。

相關文章