HTML5 Game - Image bounding animation

Description

Image bounding animation

Demo

ResultView the demo in separate window

<!DOCTYPE HTML>
<html lang = "en">
<head>
  <style type = "text/css">
    .hidden{//w w w .  j a  v  a2  s.c om
      display: none;
    }
    body {
      background-color: #cccccc;
    }
  </style>
  <script type = "text/javascript">
  let x = 0;
  let y = 100;
  let dx = 10;
  let dy = 7;
  CANV_HEIGHT = 200;
  CANV_WIDTH = 200;
  SPR_HEIGHT = 50;
  SPR_WIDTH = 50;

  function init(){
    setInterval(draw, 100);
  }

  function draw(){
    let drawing = document.getElementById("drawing");
    let con = drawing.getContext("2d");
    let myImage = document.getElementById("myImage");
    
    x += dx;
    y += dy;

    con.fillStyle = "white";
    //clear background
    con.fillRect(0, 0, 200, 200);
    con.drawImage(myImage, x, y, SPR_HEIGHT, SPR_WIDTH);
    bounce();
  }
  function bounce(){
    if (x > CANV_WIDTH - SPR_WIDTH){
      dx *= -1;
    }
    if (x < 0){
      dx *= -1;
    } 
    if (y > CANV_HEIGHT - SPR_HEIGHT){
      dy *= -1;
    } 
    if (y < 0){
      dy *= -1;
    }
  }
  </script>
</head>

<body onload = "init()">
  <h1>Bounce</h1>

  <img class = "hidden"
       id = "myImage"
       src = "http://java2s.com/style/demo/jet.png"
       alt = "my image" />

  <canvas id = "drawing"
          height = "200"
          width = "200">
    <p>Canvas not supported</p>
  </canvas>

</body>
</html>

Related Topic