Aracılığıyla paylaş


Quickstart: drawing to a canvas (HTML)

[ This article is for Windows 8.x and Windows Phone 8.x developers writing Windows Runtime apps. If you’re developing for Windows 10, see the latest documentation ]

The canvas element produces a rectangular bitmap canvas on your page where you can use JavaScript to draw graphic images on the fly. The canvas is great for creating games or any situation in which you’re generating graphics in real time or changing them at regular intervals.

This quickstart contains the following sections:

  • Prerequisities
  • The canvas element
  • Rendering contexts
  • Drawing rectangles
  • Using paths
  • Drawing arcs
  • Drawing curves
  • The quadratic curve
  • The bezier cubic curve
  • Next steps

Prerequisites

This topic assumes that you can create a basic Windows app using JavaScript that uses the Windows Library for JavaScript template, and that you have a basic understanding of HTML and JavaScript. For instructions on creating your first Windows app using JavaScript, see Create Your First Web App. For instructions on using the WinJS template, see How To Obtain and Use the WinJS Toolkit.

The canvas element

The canvas element produces a rectangular bitmap canvas on your page where you can use JavaScript to render graphic images on the fly.

The canvas element has width and height attributes. Both are optional and can be set using Document Object Model (DOM) properties. If you don't set width and height attributes, the canvas appears at its default size of 300 pixels wide and 150 pixels high.

<canvas id="canvas" width="150" height="150"></canvas>

The id attribute is not part of the canvas element but it is used to identify the canvas element in your script.

You can set the size of the canvas by using Cascading Style Sheets (CSS). By default, your app renders the canvas element with no content or border - it’s completely transparent. However, you can style it just like any normal image by specifying a margin, border, background, and so forth. Styling does not affect the actual drawing on the canvas.

Rendering contexts

Adding a canvas element to your app just creates a transparent drawing surface. To draw to the canvas, you obtain a rendering context from the canvas and use it to draw. There are different types of rendering contexts that enable you to draw in different ways. For example, there’s a 2-D context for 2-D graphics and a 3-D context for 3-D graphics. The examples in this topic use the 2-D rendering context.

To obtain a rendering context, you call the getContext method of the canvas, as shown in the following example:

var canvas = document.getElementById("quickstart");
var context = canvas.getContext("2d");

In our example, we begin by using getElementById to retrieve the canvas DOM node and then use the getContext method to access the rendering context. The getContent method takes one parameter, the type of context. In our example it is ‘2d’.

After you’ve obtained a rendering context, you can use it to draw. The next sections describe how to draw different types of shapes.

Drawing rectangles

There are two functions that be used to draw rectangles on a canvas:

  • fillRect

    fillRect (x, y, width, height)

    The method draws a filled rectangle.

    The x, y parameters are coordinates that position the rectangle on the canvas and are relative to the top left corner of the canvas. The width and height are measured in pixels.

  • strokeRect

    strokeRect(x, y, width, height)

    The strokeRect parameters are the same as for the fillRect. The difference is that the strokeRect draws only the outline of a rectangle.

This method colors a specified shape:

  • fillStyle

    fillStyle = color

    The fillStyle method uses a single parameter to fill a shape with a color. The color can be set using RGB, a pre-defined color, such as "red", "blue", and so forth, a hexadecimal color, or even a gradient. For fillStyle examples see the Drawing Rectangles example below.

This method clears the specified area and makes it fully transparent:

  • clearRect

    clearRect(x, y, width, height)

    As with the fillRect and strokeRect methods, the clearRect parameters x and y position the rectangular area to clear, and to set the width and height of the rectangle.

Example

Let’s begin with an example that will produce a canvas, and draw two filled squares; a gold square and a transparent purple square. CSS will be used to create a black border around the canvas:

Two filled squares.

The example begins by declaring a canvas element in the <body> of the HTML. The canvas element is assigned an id attribute called "canvas", and the height and width attributes of the element are set to 100 pixels:

<body>
   <canvas id="canvas" width="100" height="100" />
</body>

The canvas element is created with a one pixel wide, solid black border using a CSS. The CSS should be contained in an external file to make file loading as efficient as possible:

/* style the canvas element with a black border. */
canvas { border: 1px solid black; }

Our JavaScript code, which draws the two filled rectangles on the canvas, is also contained in an external file. It begins after the HTML document loads by using the window onload event handler to call the draw function.

window.onload = draw;

The draw method gets the canvas element using the getElementById method. It then calls the getContext method to get the drawing context. You must pass the string "2d" to the getContext method.

Every canvas has a drawing context. The drawing context is where all the drawing methods and properties are defined.

// Get the canvas element.
var canvas = document.getElementById("canvas");

// Specify a 2-D drawing context.
var context = canvas.getContext("2d");

To begin drawing the first square the fillStyle is set to a color. There are several ways to fill a rectangle. In our example we are using the RGB equivalent of gold:

context.fillStyle = "rgb(255, 215, 0)";

Here are some other ways to set the fillStyle.

  • If they are available, you can use predefined colors such as "yellow", "orange", "purple", and so forth:

    context.fillStyle = "gold";

  • Or, use the hexadecimal representation of the color form #RRGGBB:

    context.fillStyle = "#FFD700";

    This hex number is a deep gold color.

  • Though not thought of as a color, you can use a gradient for your fillStyle:

    var myGradient=context.createLinearGradient(20, 20, 100, 0);
    
    myGradient.addColorStop(0,"goldenrod");
    myGradient.addColorStop(1,"white");
    
    context.fillStyle = myGradient;
    

    This example creates a linear gradient, sets the color stops, and causes the rectangle to be drawn with the color fading from goldenrod to white.

    Two filled squares.

  • The default fillStyle is solid black.

Next we actually draw the rectangle using the fillRect method. The fillRect values start drawing a filled rectangle by setting the x and y coordinates for the top left of the rectangle at 15, 15. The x, y coordinates are relative to the top left corner of the canvas. The width and height of the rectangle are set at 55 and 50 pixels respectively:

context.fillRect (15, 15, 55, 50);

For the second rectangle, the fillStyle is set to the RGB equivalent of purple. The fourth value, the “A”, or Alpha, in RGBA, is set at 0.5 and determines the opacity of the color. Valid Alpha values are from 0.0 (fully transparent) to 1.0 (fully opaque):

context.fillStyle = "rgba(0, 0, 200, 0.5)"

The fillRect values start drawing at x and y coordinates for the top left of the rectangle at 40, 40. The width and height of the rectangle are set at 45 and 40 pixels respectively:

context.fillRect (40, 40, 45, 40);

Here are the complete code examples:

This is the JavaScript code. In our example this file would be named myJavascript.js:

window.onload = draw;   

// This function is called on page load.
function draw() {

    // Get the canvas element.
    var canvas = document.getElementById("canvas");

    // Specify a 2d drawing context.
    var context = canvas.getContext("2d");

    // Set the color to the RGB equivalent of gold.
    context.fillStyle = "rgb(255, 215, 0)";

    // Draw the rectangle.
    context.fillRect (15, 15, 55, 50);

    // Set the color to the RGB equivalent of purple and
    // set the opacity of the rectangle to 50 percent.
    
    context.fillStyle = "rgba(0, 0, 200, 0.5)"

    // Draw the rectangle.
    context.fillRect (40, 40, 45, 40);
}

This is the HTML file:

<!DOCTYPE html>
<html>
    <head>
        <script type="text/javascript" src="myJavascript.js" defer="defer"></script>
        <link Rel="stylesheet" Href="myStyle.css" Type="text/css">
    </head>
    <body>
        <canvas id="canvas" width="100" height="100" />
    </body>
</html>

Using Paths

The beginPath method starts a new path, and uses additional methods such as moveTo, lineTo, or arc to draw a combination of lines, curves and other shapes.

Once a path is created, you can use fillStyle or strokeStyle methods to render the path to the canvas.

Example

This example will use draw a brown triangle:

A filled triangle

We'll use the same HTML and CSS files as we used for the first example. In our myJavascript JavaScript file we'll use the same draw function and again call it after the HTML has loaded.

After getting the canvas element, and specifying a 2-D canvas type, we begin drawing the brown triangle by calling the beginPath method.

context.beginPath();

Internally, paths are stored as a list of sub-paths (lines, arcs, etc) which together form a shape. Every time the beginPath method is called, the list is reset and we can start drawing new shapes.

Before drawing any lines you’ll need to call the moveTo function. The moveTo function doesn’t draw anything, it is like placing a pen or pencil on spot you want to begin drawing the triangle.

context.moveTo(28, 20);

The moveTo takes two arguments, the x and y coordinates. Here we’ve set the x coordinate to 28 and y coordinate to 20. The coordinates are relative to the border of the canvas you are drawing on.

Now we’ll draw the lines of the triangle using the lineTo function. Like the moveTo function, the lineTo function has two arguments, the x and y coordinates, which are the end-points of the line we’re drawing:

context.lineTo(78, 50); 
context.lineTo(28, 78); 
context.lineTo(28, 20); 

In our example we set the fillStyle property to a hexadecimal value for brown. As discussed under the Drawing Rectangles section, the fillStyle property can be an RGB, hexadecimal color, a predefined color, or a gradient.

context.fillStyle = "#996633";

We are using the fillStyle to paint the triangle a solid brown. We could use the strokeStyle function which would paint just the outline of the shape.

Now draw the triangle shape.

context.fill();

Here is the entire JavaScript code:

    // Get the canvas element.
    var canvas = document.getElementById("canvas");

    // Specify a 2-D canvas type.
    var context = canvas.getContext("2d");
           
    // Add the brown triangle.
    context.beginPath();
    context.moveTo(28, 20);
    context.lineTo(78, 50); 
    context.lineTo(28, 78); 
    context.lineTo(28, 20); 
          
    // Set the color to the hexadecimal equivalent of brown.
    // Omit this step and the triangle will render 
    // the default color of black.
    context.fillStyle = "#996633";

    // Draw the triangle.
    context.fill();  

Drawing arcs

For drawing arcs or circles we use the arc method:

context.arc(x, y, radius, startingAngle, endingAngle, antiClockwise);

This method takes five parameters:

  • X and y are the coordinates of the circle's center.
  • The radius is the distance from the center of the circle to a point on the circle.
  • The startingAngle and endingAngle parameters define the start and end points of the arc in radians, which are measured from the x axis.
  • The anticlockwise parameter is a Boolean value which when true draws the arc anticlockwise, otherwise in a clockwise direction.

Example

This example will draw a blue circle.

A blue circle

After getting the canvas element, and specifying a 2-D canvas type, we begin drawing our circle by calling the beginPath method.

context.beginPath();

Our earlier rectangle and triangle examples we used the fillStyle function to fill in and color the shapes. This example we set the RGB color to blue and draw just the outline of the circle using the strokeStyle.

// Define the stroke color in RGB for blue.
context.strokeStyle = "rgb(0, 162, 232)";

The arc function is defined as follows:

// Define the circle using an arc.
context.arc(50, 50, 32, 0, 2 * Math.PI, true);

Where:

  • The x and y coordinates place the center of the circle at 50, 50, respectively.
  • The radius of the circle is set to 32.
  • The beginning and end of the circle are set at 0 and "2 * Math.PI" radians, which is a complete circle.
  • The anticlockwise parameter is set to true, not very important when drawing a complete circle but definitely would be important for part of an arc.

Lastly the stroke function is used to draw the circle we’ve just defined:

// draw the circle.
context.stroke();

Here is what our circle would look like if we only drew ½ of the arc, or from zero to Math.PI:

// Define the circle using an arc.
context.arc(50, 50, 32, 0, Math.PI, true);

Half stroked circle.

Here is the JavaScript code. Again, this code would be contained in a draw function that is called after the HTML page has loaded. See the Drawing Rectangles section for a complete example of the HTML or JavaScript files.

// Get the canvas element.
var canvas = document.getElementById("canvas");

// Specify a 2-D canvas type.
var context = canvas.getContext("2d");
          
// Start the path.
context.beginPath();

// Define the stroke color in RGB for blue.
context.strokeStyle = "rgb(0, 162, 232)";

// Define the circle using an arc.
context.arc(50, 50, 32, 0, 2 * Math.PI, true);

// draw the circle.
context.stroke();

Drawing curves

Curves are used to draw complex shapes. There are two types of curves; the Bezier or cubic, and the quadratic. Both have a start and end point on the canvas however how the curve is drawn is based on a control point or points. The quadratic curve has one control point, while a cubic Bezier curve uses two control points. Curves are always contained in a path.

The quadratic curve

Here is the quadraticCurveTo method:

quadraticCurveTo(cp1x, cp1y, X, Y)

The four parameters are two pairs of X, Y coordinates, the first; cp1x and cp1y is the location of the control point on the curve and the second pair is the location of the end of the curve.

As with all shapes the curve is started with a moveTo(x, y) method which supplies the x and y coordinates for the start of the curve.

Two imaginary tangential lines are drawn from the end points to the control point. The curve is drawn by a line as it moves around the tangential:

A quadrant control point.

Example

This example uses a series of quadraticCurveTo methods to draw an abstract figure with a wavy base. Note that the closer the control points are to the end point the smaller the curve becomes in the wavy base.

A quadratic curve.

We start by getting the canvas element, and specifying a 2-D canvas type. Then we create the path by calling the beginPath method.

context.beginPath();

And set our starting point for the first curve at x and y coordinates of 75 and 25, respectively.

context.moveTo(75, 25);

Each of the quadratic curves is set as follows:

context.quadraticCurveTo(10, 80, 40, 130);
context.quadraticCurveTo(30, 90, 50, 130);
context.quadraticCurveTo(50, 100, 70, 130);
context.quadraticCurveTo(80, 110, 100, 130);
context.quadraticCurveTo(120, 120, 140, 130);

Where each of the parameters is:

  • cp1x
    The x-coordinate of the control point.

  • cp1y
    The y-coordinate of the control point.

  • x
    The x-coordinate of the end point of the curve.

  • y
    The y-coordinate of the end point of the curve.

Note that the order that the curves is drawn in is important. You can remove a curve or two, or changed the order they are drawn in to see how the curves are constructed.

The color is set to green by setting the fillStyle equal to RGB values for green.

context.fillStyle = "rgb(100, 200, 50)";

Lastly the shape is colored with the fill function:

context.fill();

Note that for this example, and the next, the size of the canvas has been increased to 150 by 150 pixels:

<canvas id="canvas" width="150" height="150" />

Here is the complete example:

// Get the canvas element.
var canvas = document.getElementById("canvas");

// Specify a 2-D canvas type.
var context = canvas.getContext("2d");
         
// Create the path.
context.beginPath();

// Set the starting point for the curve.
context.moveTo(75,25);

// Set each of the curves.        
context.quadraticCurveTo(10, 80, 40, 130);
context.quadraticCurveTo(30, 90, 50, 130);
context.quadraticCurveTo(50, 100, 70, 130);
context.quadraticCurveTo(80, 110, 100, 130);
context.quadraticCurveTo(120, 120, 140, 130);

// Set the color of the image to green.
context.fillStyle = "rgb(100, 200, 50)";

// Draw the image.
context.fill();

The bezier cubic curve

Here is the bezierCurveTo method:

bezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y)

The six parameters are three pairs of X, Y coordinates; cp1x and cp1y is the location of the first control point on the curve, cp2x and cp2y is the location of the second control point, and the third pair is the location of the end of the curve.

The curve begins with the x and y coordinates in the moveTo(x, y) method.

Imaginary tangential lines are drawn from the control points to the end points. The curve is drawn by a line as it moves around the tangential lines as shown by the purple lines in the illustration:

Cubic control points.

Example

This example uses a series of bezierCurveTo methods to draw an abstract figure with a wavy base.

A cubic curve example.

After we get the canvas element, and specifying a 2-D canvas type, we create the path by calling the beginPath method.

context.beginPath();

And set our starting point for the first curve at x and y coordinates of 75 and 25, respectively.

context.moveTo(75, 25);

Each of the cubic Bezier curves is set as follows:

context.bezierCurveTo(10, 100, 10, 122, 20, 130);
context.bezierCurveTo(20, 100, 20, 122, 30, 130);
context.bezierCurveTo(40, 100, 40, 122, 50, 130);
context.bezierCurveTo(70, 100, 70, 122, 80, 130);
context.bezierCurveTo(110, 100, 110, 122, 120, 130);
context.bezierCurveTo(160, 100, 160, 122, 170, 130);

Where each of the parameters is:

  • cp1x
    The x-coordinate of the first Bézier control point.

  • cp1y
    The y-coordinate of the first Bézier control point.

  • cp2x
    The x-coordinate of the second Bézier control point.

  • cp2y
    The y-coordinate of the second Bézier control point.

  • x
    The x-coordinate of the end point of the curve.

  • y
    The y-coordinate of the end point of the curve.

Note that the order that the curves is drawn in is important. You can remove a curve or two, or changed the order they are drawn in to see how the curves are constructed.

The color is set to red by setting the fillStyle equal to RGB values for red.

context.fillStyle = "rgb(200, 0, 0)";

Lastly the shape is colored with the fill function:

context.fill();

Note that for this example, the size of the canvas has been increased to 150 by 150 pixels:

<canvas id="canvas" width="150" height="150" />

Here is the complete code example:

// Get the canvas element.
var canvas = document.getElementById("canvas");

// Specify a 2-D canvas type.
var context = canvas.getContext("2d");

// Create the path.
context.beginPath();

// Set the starting point for the curve.
context.moveTo(75, 25);
 
// Set each of the curves.
context.bezierCurveTo(10, 100, 10, 122, 20, 130);
context.bezierCurveTo(20, 100, 20, 122, 30, 130);
context.bezierCurveTo(40, 100, 40, 122, 50, 130);
context.bezierCurveTo(70, 100, 70, 122, 80, 130);
context.bezierCurveTo(110, 100, 110, 122, 120, 130);
context.bezierCurveTo(160, 100, 160, 122, 170, 130);

// Set the color of the image to red.
context.fillStyle = "rgb(200, 0, 0)";

// Draw the image.
context.fill();

Next steps

In this quickstart we added a canvas element to create a transparent drawing surface, created a border around it using CSS, and used JavaScript to draw graphic images on it.

We obtained a 2-D drawing context from the canvas element so that we could set the fillRect and fillStyle to draw rectangles. We set the fillStyle in various ways to color the graphics such as RGB, Hex values, predefined colors, and a gradient.

We saw how the beginPath method starts a new path, and uses additional methods such as moveTo, lineTo, or arc to draw a combination of lines, circles, and curves.

Once the path was created, we used fillStyle and strokeStyle methods to render the path to the canvas.

Next you will learn how to animate canvas graphics and how to create a gradient.

How to animate canvas graphics

How to create a gradient