HTML Canvas scale() mirror objects

Description

HTML Canvas scale() mirror objects

View in separate window


<!DOCTYPE HTML>
<html>
<head>
<script>
  // mirror objects

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

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

    // IMAGE variable and source.
    let ball = new Image();
    ball.src = "image2.png";

    // BALL variables.
    let ballXPos = 75;
    let ballYPos = 15;
    let ballWidth = 90;
    let ballHeight = 90;

    // REFLECTION variables.
    let reflectAdj = 3.5;
    let reflectAlpha = .4;
    let reflectY = (2 * ballYPos) + (2 * (ballHeight - reflectAdj));

    // GRADIENT for surface.
    let gradLV = context.createLinearGradient(0, 0, 0, canvas.height);

    // LOAD image of ball.
    ball.onload = function() {
      // COLORS for surface
      gradLV.addColorStop(0, "lightskyblue");
      gradLV.addColorStop(.3, "orange");
      gradLV.addColorStop(1, "blue");

      // DRAW surface.
      context.fillStyle = gradLV;
      context.fillRect(0, 0, canvas.width, canvas.height);

      // DRAW original image at specific size.
      context.drawImage(ball, ballXPos, ballYPos, ballWidth, ballHeight);

      // TRANSLATE Y position to base of image.
      context.translate(0, reflectY);

      // SCALE to create reflected image.
      context.scale(1, -1);

      // TRANSPARENCY of reflected image.
      context.globalAlpha = reflectAlpha;

      // DRAW reflected image.
      context.drawImage(ball, ballXPos, ballYPos, ballWidth, ballHeight);
    }
  }
</script>
</head>
<body>
  <div style="width: 400px; height: 210px; margin: 0 auto; padding: 5px;">
    <canvas id="canvasArea" width="400" height="210"
      style="border: 2px solid black">
You're browser doesn't currently support HTML5 Canvas.
</canvas>
  </div>
</body>
</html>



PreviousNext

Related