HTML5 Canvas [63]
and it will function properly.
Copying from One Canvas to Another
The canvas allows us to use another canvas as the source of a bitmap drawing operation. Let’s take a quick look at how we might utilize this functionality.
We will need to modify the base file for this chapter and create an extra tag in our HTML. We will name this extra element canvas2 (it can be given any id as long as it is not the same id as the first ). Here is what our HTML will look like now:
Your browser does not support HTML5 Canvas.
Your browser does not support HTML5 Canvas.
We will place the second below the original, and give it a width and height of 32. We will also need to create a new context and internal reference variable for canvas2. Here is the code that will be used to provide a reference to both elements:if (!canvasSupport()) {
return;
}else{
var theCanvas = document.getElementById("canvas");
var context = theCanvas.getContext("2d");
var theCanvas2 = document.getElementById("canvas2");
var context2 = theCanvas2.getContext("2d");
}
Example 4-17 will use the tile sheet image from earlier examples and draw it to the first canvas. It will then copy a 32×32 square from this canvas and place it on the second canvas.
Example 4-17. Copying from one canvas to another
CH4EX17: Canvas Copy
Your browser does not support HTML5 Canvas.
Your browser does not support HTML5 Canvas.
Figure 4-14 shows the canvas copy functions in operation.
Figure 4-14. An example canvas copy operation
Canvas copy operations can be very useful when creating applications that need to share and copy image data across multiple
instances on (and the Canvas object within) a web page. For example, multiple Canvas elements can be spread across a web page, and as the user makes changes to one, the others can be updated. This can be used for fun applications, such as a “minimap” in a game, or even in serious applications, such as stock portfolio charting and personalization features.
What’s Next
We covered quite a lot in this chapter, evolving from simply loading images to animating and rotating them. We looked at using tile sheets and tile maps, and then we built some useful applications with Canvas image functions and capabilities. In the first four chapters, we covered most of what Canvas offers as a drawing surface. In the next six chapters, we will cover some more advanced topics, such as applying 2D physics to Canvas objects, integrating the HTML5 and tags with the tag, creating games, and looking at some libraries and features that we can use to extend the
®Online Book Reader