Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.

  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint
Share this Page URL
Help

9. <canvas> > 9.5. Pulling External Images into a <canvas> Drawing

9.5. Pulling External Images into a <canvas> Drawing

Problem

You have an existing image (graphic, icon, photo, etc.) in an external file that you want to put into a canvas element, so that you can then manipulate or embellish it with canvas API drawing commands.

Solution

First, either load the image in question using an img tag in your markup and get a reference to it, or create an Image element dynamically in your JavaScript code:

var img = new Image();
img.src = "http://somewhere/to/my/image.jpg";

Next, once the image is loaded, draw the image onto a canvas element:

var img = new Image();
img.onload = function() {
    // note: we're calling against the "2d" context here
    mycontext.drawImage(img, 0, 0); // draw the image at (0,0)
};
img.src = "http://somewhere/to/my/image.jpg";

  

You are currently reading a PREVIEW of this book.

                                                                                                                    

Get instant access to over $1 million worth of books and videos.

  

Start a Free Trial


  
  • Safari Books Online
  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint