HTML and CSS Reference
In-Depth Information
//draw image
var img=new Image();
img.src="test.jpg";
img.onload = function(){
context.drawImage (img,0,0);
};
</script>
As you can see from the listing script, I created a new image object,
img
, and assigned its source to
test.jpg
(note
that this will change with whatever image path you use). Once the image is loaded, it will fire the event onload, which
will execute the function to call
drawImage
and paint the image onto the
canvas
element.
Events
As you've become aware, the
canvas
element is a great feature in HTML5 for rendering both vector and bitmap
graphics to the screen. But it's not finished there. The
canvas
can also react; it can handle events from the browser or
from user inputs, including mouse, touch, and DOM events. Listing 4-8 showcases how the
canvas
can react to many
events by logging output into the JavaScript console in your browser.
Listing 4-8.
Using Canvas to Log Output into the JavaScript Console
<script type="text/javascript">
//get a reference to the canvas
var canvas = document.getElementById('adCanvas');
var context = canvas.getContext('2d');
//Mouse Events
canvas.addEventListener('click', function(evt){
console.log('Click: ' + evt);
});
canvas.addEventListener("mouseover", function(evt) {
console.log('MouseOver: ' + evt);
});
canvas.addEventListener("mouseout", function(evt) {
console.log('MouseOut: ' + evt);
});
canvas.addEventListener("mousemove", function(evt) {
console.log('MouseMove: ' + evt);
});
//Touch Events
canvas.addEventListener("touchstart", function(evt) {
console.log('TouchStart: ' + evt.touches.length);
});
canvas.addEventListener("touchmove", function(evt) {
evt.preventDefault();
var touch = evt.touches[0];
console.log("Touch x:" + touch.pageX + ", y:" + touch.pageY);
});
canvas.addEventListener("touchend", function(evt) {
console.log('TouchEnd: ' + evt);
});