HTML5 Game - Creating an image from scratch

Introduction

To create pixels, call the createImageData method of the 2d rendering context.

The following code creates an ImageData object with an area of 200 by 200, and then change them all to red.

 
      
<!DOCTYPE html>

<html>
  <head>
    <title>Manipulating images and video</title>
    <meta charset="utf-8">
    
    <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");
        
        // Drawing pixels to the canvas
        let imageData = context.createImageData(200, 200);
        let pixels = imageData.data;
        let numPixels = imageData.width*imageData.height;
        
        // Access and change pixel values
        for (let i = 0; i < numPixels; i++) {
          pixels[i*4] = 255; // Red
          pixels[i*4+1] = 0; // Green
          pixels[i*4+2] = 0; // Blue
          pixels[i*4+3] = 255; // Alpha
        };
        
        // Draw image data to the canvas
        context.putImageData(imageData, 0, 0);
      
      });
    </script>
  </head>
  
  <body>
    <canvas id="myCanvas" width="500" height="500">
      <!-- Insert fallback content here -->
    </canvas>
  </body>
</html>

Related Topic