Applying colors

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.

Getting ready

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.

How to do it...

  1. We'll start by saving the file generated for the previous file as 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();
    
  2. Repeat the process for the other figures. You can even change the color assigned for the fillStyle property. For example, we can use #295ea0 for the figure at the bottom and #ffffff for the circle.
  3. When you're ready, reload your new page in your device. The result will be as shown in the next screenshot:
    How to do it...
  4. You can take a look at the complete code used by this recipe at: code/ch04/colors.html.

How it works...

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.

Note

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.

See also

  • Installing the iWebKit framework recipe in Chapter 1 , Frameworks Make Life Easier.
  • Drawing geometric figures recipe
  • Working with gradients recipe
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.225.57.164