HTML5 Game - Draw shape on grid

Description

Draw shape on grid

Demo

ResultView the demo in separate window

<!doctype html>
<html>
  <head>
    <title>More drawing to canvas</title>
    <style>
body {/*ww  w.  j  ava  2  s  .  c  o  m*/
  text-align: center;
  font-family: sans-serif;
}
canvas {
  background-color: black;
  border: 10px solid white;
}

canvas:focus {
  border: 10px solid grey;
}
</style>

  </head>
  <body>
    <h1>More drawing to canvas</h1>
    <canvas id="balls" width="400" height="400"></canvas>
    <script>
      let canvas = document.getElementById("balls");
      let context = canvas.getContext("2d");
      context.fillStyle = 'grey';
      context.fillRect(0, 0, 400, 400);


      function draw_grid(ctx, minor, major, stroke, fill) {
        minor = minor || 10;
        major = major || minor * 5;
        stroke = stroke || "#00FF00";
        fill = fill || "#009900";
        ctx.save();
        ctx.strokeStyle = stroke;
        ctx.fillStyle = fill;
        for(let x = 0; x < ctx.canvas.width; x += minor) {
          ctx.beginPath();
          ctx.moveTo(x, 0);
          ctx.lineTo(x, ctx.canvas.height);
          ctx.lineWidth = (x % major == 0) ? 0.5 : 0.25;
          ctx.stroke();
          if(x % major == 0 ) {ctx.fillText(x, x, 10);}
        }
        for(let y = 0; y < ctx.canvas.height; y += minor) {
          ctx.beginPath();
          ctx.moveTo(0, y);
          ctx.lineTo(ctx.canvas.width, y);
          ctx.lineWidth = (y % major == 0) ? 0.5 : 0.25;
          ctx.stroke();
          if(y % major == 0 ) {ctx.fillText(y, 0, y + 10);}
        }
        ctx.restore();
      }

      draw_grid(context);


      context.beginPath();
      context.strokeStyle = "#FFFFFF";
      context.fillStyle = "#00FF00";
      context.lineWidth = 2;
      context.moveTo(50, 50);
      context.lineTo(150, 250);
      context.lineTo(250, 170);
      context.lineTo(320, 280);
      context.closePath();
      context.stroke();
      context.fillText("(50, 50)", 30, 40);
      context.fillText("(150, 250)", 130, 260);
      context.fillText("(250, 170)", 255, 175);
      context.fillText("(320, 280)", 325, 285);


      context.beginPath()
      context.moveTo(50, 250);
      context.lineTo(50, 350);
      context.lineTo(150, 350);
      context.closePath();
      context.moveTo(230, 360);
      context.lineTo(270, 360);
      context.lineTo(270, 310);
      context.closePath();
      context.moveTo(250, 50);
      context.lineTo(370, 50);
      context.lineTo(370, 100);
      context.closePath();
      context.strokeStyle = "red";
      context.fillStyle = "grey";
      context.fill();
      context.stroke(); 

    </script>
  </body>
</html>

Related Topic