HTML and CSS Reference
In-Depth Information
context.fillStyle = "rgba(0,0,255,.4)";
context.rect(50,50,100,100);
context.fill();
}
</script>
</head>
<body>
<h1>
Simple Transforms
</h1>
<canvas id="canvas" width="400" height="300">
<strong>
Canvas Supporting Browser Required
</strong>
</canvas>
</body>
</html>
O
NLINE
http://htmlref.com/ch2/canvastransform.html
Using Bitmaps in Drawings
A very interesting feature of
canvas
is the ability to insert images into the drawing There
are several ways to do this, but let's start with the most basic,
drawImage(
img
,
x
,
y
)
, which
takes an image object and the coordinates for where the image should be placed. The image
will be its natural size when called in this manner. You can use
drawImage(
img
,
x
,
y
,
w
,
h
)
if you need to modify the image size and set the width and height.
The actual image passed in to the
drawImage()
method can come from a few places.
It can be
•
An image already loaded on the page
•
Dynamically created through the DOM
•
Another
canvas
object
•
An image created by setting its
src
to a
data:
URL
The important thing to remember is that the image must be loaded by the time
canvas
is ready to access it. This may require use of the
onload
function for the image:
var img = new Image();
img.onload = function(){
context.drawImage(img,0,0,400,400);
}
img.src = "dog.jpg";
The last way that
drawImage(
img
,
sx
,
sy
,
sw
,
sh
,
dx
,
dy
,
dw
,
dh
)
may be called allows
a part of the image to be cut out and drawn to the
canvas
. The (
sx
,
sy
) coordinates are the
location on the image, and
sw
and
sh
are the width and height, respectively. The rest of the
parameters prefixed with
d
are the same as in the previous form of the method.
var img = document.getElementById("image1");
/* slices a 100px square from image1 at location (200,75)
Places on the canvas at (50,50) and stretches it to 300px square. */
context.drawImage(img,200,75,100,100,50,50,300,300);