HTML and CSS Reference
In-Depth Information
In an example, the putImageData and getImagedata API are powerful, but it can be hard to use them in games
dynamically because their speed is quite slow. I will show you alternative ways to transform color without these APIs
later in this chapter.
Path API Example
The Path API is for drawing many types of shapes, such as lines, circles, and polygons, on a HTML5 canvas. A path is
a series of points with drawing instructions between those points. Some helper APIs also exist to draw a rectangle or
circle easily. Listing 16-3 shows code that writes a character using Paths (see Figure 16-3 ).
Listing 16-3. Path Methods
onload = function() {
var canvas = document.createElement("canvas");
canvas.width = canvas.height = 300;
document.body.appendChild(canvas);
var ctx = canvas.getContext("2d");
ctx.beginPath(); ctx.moveTo(40.35, 18.6);
ctx.quadraticCurveTo(44.9, 15.6, 44.9, 10.7);
ctx.quadraticCurveTo(44.9, 5.9, 41.4, 2.95);
ctx.quadraticCurveTo(37.85, 0, 31.75, 0);
ctx.lineTo(0, 0); ctx.lineTo(0, 38.55); ctx.lineTo(31.35, 38.55);
ctx.quadraticCurveTo(46.5, 38.55, 46.45, 28.15);
ctx.quadraticCurveTo(46.45, 21.75, 40.35, 18.6);
ctx.moveTo(31.85, 15.65);
ctx.lineTo(7.55, 15.65); ctx.lineTo(7.55, 6.75); ctx.lineTo(32.1, 6.75);
ctx.quadraticCurveTo(37.55, 6.75, 37.55, 11.15);
ctx.quadraticCurveTo(37.55, 13.2, 36.05, 14.45);
ctx.quadraticCurveTo(34.5, 15.7, 31.85, 15.65);
ctx.moveTo(31.35, 31.8);
ctx.lineTo(7.55, 31.8); ctx.lineTo(7.55, 22.45); ctx.lineTo(32, 22.45);
ctx.quadraticCurveTo(38.9, 22.45, 38.9, 27.35);
ctx.quadraticCurveTo(38.9, 29.35, 36.9, 30.6);
ctx.quadraticCurveTo(34.95, 31.8, 31.35, 31.8);
ctx.fill();
};
Figure 16-3. Path methods output
As you can see, the code using a Path might be very complex and hard to maintain. If you want to use a Path
inside your game, you should prepare shapes as some data structures and parse data structures dynamically. Later in
this chapter, I will show you an effective way to achieve dynamic parsing.
 
Search WWH ::




Custom Search