Partager via


Using Canvas to Add Texture to Photos

This topic explains how you can use HTML5 Canvas to add a texture to a photograph for artistic effect.

  • Canvas Code Sample
  • Canvas Code Sample Discussion
  • Body Code
  • Script Code
    • displayImage Function
    • changeImage Function
    • Code Requirements
  • Related topics

This topic includes a stand-alone annotated code sample that shows how to add a snow-like texture to the photograph of an American Kestral falcon. The code sample demonstrates how to use Canvas to load the falcon photograph into a webpage and display it on the screen. Then, it shows how to use the Canvas arc method to draw 50 tiny white circles around the bird to make it appear as if it is snowing. The discussion material at the end of this sample will explain more about how the code works to develop this technique.

Canvas Code Sample

<!DOCTYPE html>
<html>
  
  <head>
    <script type="text/javascript">
    
      //Global variables
      var myImage = new Image(); // Create a new blank image.
      
      // Load the image and display it.
      function displayImage() {

        // Get the canvas element.
        canvas = document.getElementById("myCanvas");

        // Make sure you got it.
        if (canvas.getContext) {

          // Specify 2d canvas type.
          ctx = canvas.getContext("2d");

          // When the image is loaded, draw it.
          myImage.onload = function() {

            // Load the image into the context.
            ctx.drawImage(myImage, 0, 0);

            // Get and modify the image data.
            changeImage();
          }

          // Define the source of the image.
          myImage.src = "http://samples.msdn.microsoft.com/workshop/samples/canvas/kestral.png";
        }
      }

      function changeImage() {

         // Draw snowflakes.
        for (i = 0; i <= 50; i++) {
          // Get random positions for flakes.
          var x = Math.floor(Math.random() * 199);
          var y = Math.floor(Math.random() * 199);

          // Make the flakes white
          ctx.fillStyle = "white";

          // Draw an individual flakes.
          ctx.beginPath();
          ctx.arc(x, y, 3, 0, Math.PI * 2, true);
          ctx.closePath();
          ctx.fill();
        }
      }
    </script>
  </head>
  
  <body onload="displayImage()">
    <h1>
      American Kestral
    </h1>
    <p>
      The original image is on the left and the modified image is on the right.
    </p>
    <img id="myPhoto" src="http://samples.msdn.microsoft.com/workshop/samples/canvas/kestral.png">
    <canvas id="myCanvas" width="200" height="200">
    </canvas>
    <p>
      Public domain image courtesy of U.S. Fish and Wildlife Service.
    </p>
  </body>

</html>

Canvas Code Sample Discussion

This discussion explains the design and structure of this Canvas code sample and how all the parts work together. The sample uses a standard HTML5 header, <!doctype html>, so that browsers can distinguish it as part of the HTML5 specification. This code is divided into two major parts:

  • Body Code
  • Script Code

Body Code

The body tag uses the onload function to call the displayImage function when the page is loaded. An original image of a kestral is loaded into the body so you can compare it to the one that will be modified by Canvas. The canvas tag is part of the body. The initial width and height of the Canvas is specified, as is the id attribute. The ID is required so that the canvas element can be added to the object model of the page.

Script Code

The script code includes two functions: displayImage and getColorData. The displayImage function is called when the page is loaded. The getColorData function is called from displayImage. A global variable is created at the beginning of the script section to create an empty image file, which will be used later.

displayImage Function

This function is called on page load. It gets the canvas by using the ID of the canvas element in the body code. It then gets the CanvasRenderingContext2D object of the canvas, making it ready to accept drawing and uses DrawImage to load the image into the context. After the context is initialized as a 2-D canvas, the canvas is ready to be drawn upon.

The last thing the function does is to specify the source of the image by supplying a path. Because images might not load instantly, an event is set up that calls a function when the image actually gets loaded. After the image is loaded, it is displayed, and a call is made to the changeImage function, which completes the drawing work.

changeImage Function

The image is modified by drawing 50 small circles by using the arc method. Fifty star locations are calculated and the fillStyle is specified as "white." Then the flakes are drawn with a radius of 3 pixels and filled with white, by using the beginPath method, the arc method, the closePath method, and the fill method.

Code Requirements

This code runs in Windows Internet Explorer 9. It will not work in earlier versions of Windows Internet Explorer, but might run in other browsers that support HTML5 Canvas.

How to Create Canvas Special Effects