HTML and CSS Reference
In-Depth Information
canvas.addEventListener("touchcancel", function(evt) {
console.log('TouchCancel: ' + evt);
});
</script>
User input is being handled on mouse clicks and touch events, and the output is logged to the JavaScript console.
Keep in mind that you can extend this to a user painting with their mouse or even finger, should the device support it.
Having user inputs with the canvas element provides interactivity, a great feature to incorporate into your creative. It
could involve starting or stopping animation in the canvas or even interacting with a game inside your ad unit. Keep
this in mind when building ads that require interactivity and user input.
Saving
Now that you know how to provide interactivity by controlling user input, let's attempt to save the image on our
canvas to our local drive. To save the canvas as an image, set the image source to the image todataURL . From there, a
user can save it to a local machine. Pretty cool! Especially when you want the user to customize something within the
experience and take the art away or share it via email or on a social networking site.
Note
the toDataURL() method will throw a SECURITY_ERR exception if the canvas has paint from other domains.
Listing 4-9 showcases how to use canvas to save an image format via the toDataURL method.
Listing 4-9. Using Canvas to Save Images
<script type="text/javascript">
//get a reference to the canvas
var canvas = document.getElementById('adCanvas');
var context = canvas.getContext('2d');
var img=new Image();
img.src="test.jpg";
img.onload = function(){
context.drawImage (img,0,0);
};
//Mouse Events
canvas.addEventListener('click', function(evt){
console.log('Click: ' + evt);
// no argument defaults to image/png; image/jpeg, etc. also work on some. image/png is the only
one that must be supported per spec.
try {
window.location = canvas.toDataURL("image/png");
} catch (error) {
console.log(error);
}
});
</script>
You can now save images in your canvas container! This is really helpful if you are creating an interactive ad unit
that you want the user to draw or to create something with, if you want the user to have the ability to save it to their
machine or share it with another web service. As in Listing 4-9, paint the image to the canvas, and on mouse click
 
 
Search WWH ::




Custom Search