In the last recipe, you learned how to draw geometric figures on the screen using paths through lines and movements. You can go further by applying some styles such as colors. Fortunately, Safari Mobile provides a few JavaScript functions for applying these styles, making our job easier.
This recipe describes how to apply background colors to figures inside a canvas
element.
In order to make things easier, we're going to use our code generated for the previous recipe as a starting point. This means we'll need to have the iWebKit framework installed in our computer.
colors.html
. Then, let's go to the line ctx.stroke()
for the first figure. Delete it and insert the following two lines:ctx.fillStyle = "#3eac3e"; ctx.fill();
fillStyle
property. For example, we can use #295ea0
for the figure at the bottom and #ffffff
for the circle.code/ch04/colors.html
.Basically, we need one JavaScript method and one property for coloring our figures and shapes inside a canvas. We're talking about fillStyle
and fill()
, which are provided by the context object.
stroke()
and fill()
method have similar behavior; both are used for painting inside the canvas.
We used the HTML notation for setting colors, but you can also use the string notation or the rgba notation introduced by HTML5. For instance, using string notation, you can set white
string for the white color. Alternatively, you can use (255,255,255, 0) for the rgba notation.
18.225.57.164