HTML5 Game - Canvas Loading images

Introduction

To load an image at runtime.

Then create a new Image object and set its src property to the URL path of an image file.

Demo

ResultView the demo in separate window

<!doctype html>  
<html>  
 <head>  
  <meta charset="utf-8">  
  <title>Load Image</title>  
  <style>canvas{border:1px solid red;}</style>  
 </head>  //  w w  w  . ja  v a2 s  . c  o m
 <body>  
  <canvas id="canvas" width="400" height="400"></canvas>  
  <script>  
  window.onload = function () {  
    let canvas = document.getElementById('canvas'),  
        context = canvas.getContext('2d'),  
        image = new Image();  
      
    image.src = "http://java2s.com/style/demo/jet.png";  
    image.onload = function () {  
      context.drawImage(image, 0, 0);  
    };  
  };  
  </script>  
 </body>  
</html>

Related Topic