Export (0) Print
Expand All
This topic has not yet been rated - Rate this topic

CanvasPattern object

Provides an object that contains a pattern for a canvas fill style by using an image or portion of an image.

HTML Canvas 2D Context, Section 1Internet Explorer 9

Members

The CanvasPattern object does not define any members.

Standards information

Remarks

To create a pattern from a portion of an existing canvas image, create a temporary clip canvas and use drawImage to extract the piece. Then, pass the temporary canvas to the createPattern method.

Note  If you are developing on an intranet and have rendering issues for HTML5, you can add a "meta http-equiv-'X-UA-Compatible' content= " meta command, followed by "IE=edge" to the <head> block of a webpage to force Windows Internet Explorer to use the latest standards. For more information about document compatibility, see Defining Document Compatibility.

Examples

The following code example demonstrates each type of direction that you can repeat an image in a canvas.


<!DOCTYPE html> 
<html>
<head>
  <title>Canvas pattern example</title> 
</head>
<body>
  <h1>Canvas pattern example</h1>
    <p>This picture will appear below.</p>
    <div>
    <img id="pix" src="http://go.microsoft.com/fwlink/p/?linkid=199028" />   
    </div>
    <button onclick="draw('repeat')">Repeat all</button> 
    <button onclick="draw('repeat-x')">Repeat across</button> 
    <button onclick="draw('repeat-y')">Repeat down</button> 
    <button onclick="draw('no-repeat')">No Repeat</button><br />     
  <canvas id="MyCanvas" width="600" height="500">
    This browser or document mode doesn't support canvas
  </canvas>   
  
  <script>
    var image;
    function draw(direction) {
      var canvas = document.getElementById("MyCanvas");
      if (canvas.getContext) {
        var ctx = canvas.getContext("2d");                // Get the context.
        ctx.clearRect(0, 0, canvas.width, canvas.height);    // Clear the last image if it exists.
        image = document.getElementById("pix");       // Get the address of the picture.
        var pattern = ctx.createPattern(image, direction);// Get the direction from the button.    
        ctx.fillStyle = pattern;                          // Assign pattern as a fill style.
        ctx.fillRect(0, 0, canvas.width, canvas.height);     // Fill the canvas.   
      }
    }
    //  Start display when image is loaded. 
    image = document.getElementById("pix");
    image.addEventListener("load", function () {
      draw("repeat"); // Start display
    }, false);

  </script>

</body>
</html> 
 


See also

createPattern

 

 

Did you find this helpful?
(1500 characters remaining)
Thank you for your feedback
Show:
© 2014 Microsoft. All rights reserved.