用canvas画七巧板 -- 练习canvas

424 阅读1分钟

canvas知道绘制路径后,加强这方面的理解,就试着画了个七巧板。

首先复习下这些知识点:

  • canvas.width

  • canvas.height

  • canvas.getContext('2d')

  • context.beginPath()

  • context.moveTo(x,y)

  • context.lineTo(x,y)

  • context.closePath(x,y)

  • context.stroke(x,y)

  • context.fill(x,y)

  • context.strokeStyle='#ddd'

  • context.lineWidth=3

  • context.fillStyle='#ddd'

然后用上面的这些实现如图所示的七巧板~

七巧板

思路:将每片的路径和颜色都存放起来,然后遍历下就好了~~。

<canvas id="tutorial"></canvas>
<script>
  const canvas = document.getElementById("tutorial");
  const ctx = canvas.getContext("2d");
  canvas.width = 800;
  canvas.height = 800;

  const tangram = [
    { p: [ [0, 0], [800, 0], [400, 400] ], color: "#caff67" },
    { p: [ [0, 0], [400, 400], [0, 800] ], color: "#67becf" },
    { p: [ [800, 0], [800, 400], [600, 600], [600, 200] ], color: "#ef3d61"},
    { p: [ [600, 200], [600, 600], [400, 400] ], color: "#f9f51a" },
    { p: [ [400, 400], [600, 600], [400, 800], [200, 600] ], color: "#a594c0" },
    { p: [ [200, 600], [400, 800], [0, 800] ], color: "#fa8ecc" },
    { p: [ [800, 400], [800, 800], [400, 800] ], color: "#f6ca29" }
  ];
  const drawPiece = (piece, ctx) => {
    // 路径
    ctx.beginPath();
    var firstPoint = piece.p.shift(0);
    ctx.moveTo(...firstPoint);
    piece.p.forEach(point => ctx.lineTo(...point));
    ctx.closePath();
	
    // 状态
    ctx.fillStyle = piece.color;
    ctx.strokeStyle = "#000";
    ctx.lineWidth = 3;
    
    // 绘制
    // 在既有填充也有描边的情况下,一般先fill在stroke
    ctx.fill();
    ctx.stroke();
  };
  tangram.forEach(piece => drawPiece(piece, ctx));
</script>

慕课上liuyubobobo老师,说canvas挺好的,可以细看看他的视频,也是demo来源