HTML5 Game - Canvas Animation Image flying

Description

Image flying

Demo

ResultView the demo in separate window

<!DOCTYPE HTML>
<html lang = "en">
<head>
  <style type = "text/css">
    .hidden{/*from   w  w  w.  ja  v  a2s. co m*/
      display: none;
    }
  </style>
  <script type = "text/javascript">
  let drawing;
  let con;
  let myImage;
  CANV_HEIGHT = 200;
  CANV_WIDTH = 200;
  SPR_HEIGHT = 50;
  SPR_WIDTH = 40;

  let x = 0;
  let y = 100;
  let dx = 10;
  let dy = 7;

  function init(){
    drawing = document.getElementById("drawing");
    con = drawing.getContext("2d");
    myImage = document.getElementById("myImage");
    setInterval(draw, 100);
  }

  function draw(){
    con.clearRect(0, 0, 200, 200);
    x += dx;
    y += dy;
    wrap();
    con.drawImage(myImage, x, y, SPR_WIDTH, SPR_HEIGHT);
    con.strokeStyle = "red";
    con.lineWidth = 5;
    con.strokeRect(0, 0, CANV_WIDTH, CANV_HEIGHT);
  }

  function wrap(){
    if (x > CANV_WIDTH){
      x = 0;
    }
    if (x < 0){
      x = CANV_WIDTH;
    } 
    if (y > CANV_HEIGHT){
      y = 0;
    }
    if (y < 0){
      y = CANV_HEIGHT;
    }
  } 
  </script>
</head>

<body onload = "init()">
  <h1>Wrap</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