HTML5 Game - Draw shape via function

Description

Draw shape via function

Demo

ResultView the demo in separate window

<!doctype html>
<html>
  <head>
    <title>Drawing a spaceship</title>
  </head>/*from   w  ww. j a va2 s  . com*/
  <body>
    <h1>Drawing a spaceship</h1>
    <canvas id="balls" width="600" height="600"></canvas>
    <script>
      let context = document.getElementById("balls").getContext("2d");
function draw_ship(ctx, x, y, radius, options) {
  options = options || {};
  ctx.save();
  if(options.guide) {
    ctx.strokeStyle = "white";
    ctx.fillStyle = "rgba(0, 0, 0, 0.25)";
    ctx.lineWidth = 0.5;
    ctx.beginPath();
    ctx.arc(x, y, radius, 0, 2 * Math.PI);
    ctx.stroke();
    ctx.fill();
  }
  ctx.lineWidth = options.lineWidth || 2;
  ctx.strokeStyle = options.stroke || "white";
  ctx.fillStyle = options.fill || "black";
  let angle = (options.angle || 0.5 * Math.PI) / 2;
  ctx.beginPath();
  ctx.moveTo(x + radius, y);
  ctx.lineTo(
    x + Math.cos(Math.PI - angle) * radius,
    y + Math.sin(Math.PI - angle) * radius
  );
  ctx.lineTo(
    x + Math.cos(Math.PI + angle) * radius,
    y + Math.sin(Math.PI + angle) * radius
  );
  ctx.closePath();
  ctx.fill();
  ctx.stroke();
  ctx.restore();
}


      draw_ship(context, 200, 200, 25, {guide: true});
      draw_ship(context, 5, 75, 50, {stroke: 'gold', fill: 'purple'});
      draw_ship(context, 300, 300, 50, {angle: 0.8 * Math.PI, guide: true});
      draw_ship(context, 5, 325, 50, {angle: 0.3 * Math.PI, guide: true});
      draw_ship(context, 405, 75, 50, {lineWidth: 8, fill: 'blue'});
    </script>
  </body>
</html>

Related Topic