HTML and CSS Reference
In-Depth Information
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";
The image object you pass as the first parameter to drawImage(...) can
actually be a real image, another element, or a video element (achieved
by capturing a frame of video into your canvas ).
This assumes that your canvas element is already properly sized to be able to handle
the image that you're trying to draw into it. If it's too small in either dimension, clip-
ping occurs, with the image being cut off on the right or bottom edge, respectively.
Discussion
The canvas API gives you the drawImage(...) command to let you capture image bitmap
data from another source (an image, another canvas element, or a video element) and
draw it directly into your canvas element.
There are three ways to call drawImage(...) . The simplest form, shown above, takes an
element to capture the bitmap image data from and two coordinates, the ( X , Y ) location
inside your canvas element at which to place the top-left corner of the image.
The second form takes an additional two parameters, ( dw , dh ) , which are the width and
height of the area from the original image that you want to capture and copy to your
canvas element.
The third form of the call takes quite a few more parameters than the second form. The
first four numeric parameters, ( sx , sy , sw , sh ) , specify the top-left location and the
width/height of the area from the original source image data to capture, and the last
four parameters, ( dx , dy , dw , dh ) , represent the top-left location and the width/height of
the area where the image data will be copied to in your canvas element:
function createCanvas(id, width, height) {
var canvas = document.createElement("canvas");
canvas.id = id;
canvas.setAttribute("width", width);
canvas.setAttribute("height", height);
 
Search WWH ::




Custom Search