HTML and CSS Reference
In-Depth Information
Compared to CSS, Canvas has few issues. The APIs of Canvas 2D are simple, so there are few differences between
devices (although there are still problems.) Additionally, Canvas has the responsibility of all drawing on browsers.
This means there is the disadvantage that you have to write tons of code if you want to create animation on your web
site, but the advantage is that you can improve your code to detail with techniques and know-how.
On the other hand, CSS has original features such as CSS filters, CSS animations, CSS transforms, and so on. It is
good idea to make games using Canvas and CSS together. In addition, the evolution of modern browsers is significant.
If the market share of the Chrome browser for Android increases, CSS compatibility and speed will be improved. But
as long as you are trying to make good games on mobile HTML5, you must understand the effective ways to create
games using Canvas. You'll learn a lot about the Canvas 2D API in this chapter.
The Basis of Canvas
In short, Canvas is a kind of img element with the feature of reading and writing pixel by pixel. You can draw curved
lines, text, images, and so on, as you like. Generally you draw the Canvas properly in every frame using JavaScript.
Bitmap Images and Vector Images
The style of managing every pixel in Canvas is known as using bitmap images. Bitmap images are the kind of images
you would edit with tools like Photoshop.
The opposite is vector images. These are produced using tools such as Illustrator or Flash. Bitmap images are
based on pixels, so when scaled there is a loss of clarity, while vector images can be scaled by any amount without
degrading quality because they are based on paths, which are points, line styles, and so on. Vector images are not fit
for picture-like complex images.
Although Canvas is bitmap image-based, aiming for drawing pixel by pixel, Canvas contains APIs for both bitmap
graphics and vector graphics. So, despite common misunderstanding, you can make animations similar to Flash
animations using the Canvas 2D API.
A Bitmap API Example
There are two kinds of Bitmap APIs. One draws images, and the other deals with pixel data. Listings 16-1 and 16-2
provide example code for dealing with bitmap images.
Listing 16-1. DrawImage
onload = function() {
var img = document.createElement("img");
img.onload = function() {
var canvas = document.createElement("canvas");
canvas.width = canvas.height = 300;
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0);
(function tick() {
ctx.drawImage(canvas, 0, 0, 300, 300, 10, 10, 280, 280);
setTimeout(tick, 500);
img.src = "lenna.jpg";
Search WWH ::

Custom Search