HTML Canvas Context resize and scale

Description

HTML Canvas Context resize and scale

View in separate window

<!DOCTYPE HTML>
<html>
<head>
<script>
  //resize and scale canvas

  // SUMMARY: Draws random circles on a 
  // resized and rescaled canvas.

  window.onload = function() {/*from   w  w w.  j a  v a2  s .c  o m*/

    canvas = document.getElementById("canvasArea");
    context = canvas.getContext("2d");

    // PARAMETERS for circles.
    let numCircles = 300;
    let maxRadius = 20;
    let minRadius = 3;
    let colors = [ "aqua", "black", "blue", "fuchsia", "green", "cyan",
        "lime", "maroon", "navy", "olive", "purple", "red", "silver",
        "teal", "yellow", "azure", "gold", "bisque", "pink", "orange" ];
    let numColors = colors.length;

    // RESIZE & RESCALE canvas.
    canvas.width = 400;
    canvas.height = 100;
    context.scale(.7, .3);

    // CREATE circles.
    for (let n = 0; n < numCircles; n++) {
      // RANDOM values for circle characteristics.
      let xPos = Math.random() * canvas.width;
      let yPos = Math.random() * canvas.height;
      let radius = minRadius + (Math.random() * (maxRadius - minRadius));
      let colorIndex = Math.random() * (numColors - 1);
      colorIndex = Math.round(colorIndex);
      let color = colors[colorIndex];

      // DRAW circle.
      drawCircle(context, xPos, yPos, radius, color);
    }
  };
  // CIRCLE drawing function.
  function drawCircle(context, xPos, yPos, radius, color) {
    //PARAMETERS for shadow and angles.
    let startAngle = (Math.PI / 180) * 0;
    let endAngle = (Math.PI / 180) * 360;
    context.shadowColor = "gray";
    context.shadowOffsetX = 1;
    context.shadowOffsetY = 1;
    context.shadowBlur = 5;

    //DRAW CIRCLE
    context.beginPath();
    context.arc(xPos, yPos, radius, startAngle, endAngle, false);
    context.fillStyle = color;
    context.fill();
  }
</script>
</head>
<body>
  <!-- CANVAS definition -->
  <div style="width: 200px; height: 200px; margin: 0 auto; padding: 5px;">
    <canvas id="canvasArea" width="200" height="200"
      style="border: 2px solid black">
Your browser doesn't currently support HTML5 Canvas.
</canvas>
  </div>
</body>
</html>



PreviousNext

Related