HTML5 Game - Loading an image into canvas

Introduction

The image argument can be a HTML img element, a HTML5 canvas element, or a HTML5 video element.

The following code shows how to draw an HTML img element to the canvas.

Demo

ResultView the demo in separate window

<!DOCTYPE html>
<html>
  <head>
    <title>Manipulating images and video</title>
    <meta charset="utf-8">
    //from   w  w  w  .  jav a  2s. co m
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
    
    <script type="text/javascript">
      $(document).ready(function() {  
        let canvas = $("#myCanvas");
        let context = canvas.get(0).getContext("2d");
        
        let image = new Image();
        image.src = "http://java2s.com/style/demo/jet2.png";
        $(image).load(function() {
          context.drawImage(image, 0, 0);
        });
      });
    </script>
  </head>
  
  <body>
    <canvas id="myCanvas" width="500" height="500">
      <!-- Insert fallback content here -->
    </canvas>
  </body>
</html>

Related Topic