Canvas basics

In this section we will learn some of the basics of using the canvas API. Now that we have a context, we can call its methods to draw lines and shapes. The API has a whole host of methods that let you draw everything from the most basic lines, to shapes, and even bitmap images.

You can find the source code for this section in chapter4/canvas-examples/canvas-examples.html.

Clearing the canvas

The background of the canvas is transparent. Whatever background color you specify for the canvas element in your CSS will show through. You can clear the canvas, or a portion of it, using the context's clearRect() method. It takes x, y, width, and height parameters and clears that part of the canvas.

context.clearRect(0, 0, canvas.width, canvas.height);

Context properties

By default, when you draw on the canvas, lines are one pixel wide and the color is black. You can change these by setting global properties on the context object.

  • penWidth: This property sets the width that lines will be drawn with. It can be any decimal number. For example, you can have a line that is 1.5 pixels wide.
  • strokeStyle: This property sets the color that will be used to draw lines. It can be any one of the CSS color specifiers. For example, to draw in red you could use red or #FF0000, rgb(255, 0, 0), or rgba(255, 0, 0, 1).
  • fillStyle: This property sets the color that will be used to fill shapes. Like strokeStyle it can be any CSS color specifier.
  • globalAlpha: This property sets the alpha or transparency amount to draw with. It can be any number from 0 to 1, where 0 is completely transparent and 1 is completely opaque.
  • lineCap: This property determines how the ends of lines are drawn. It can be one of the following:
    • butt draws a flat end
    • round draws a rounded end
    • square draws a square end

    square looks similar to butt except that it has an extra rectangle drawn at the end, making it longer.

    Context properties
  • lineJoin: This property determines how corners are drawn where two lines meet. It can be one of the following:
    • bevel draws a beveled or flat corner
    • round draws a rounded corner
    • miter draws a sharp corner
    Context properties
..................Content has been hidden....................

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