JavaScript Tutorial JavaScript Examples JQuery Tutorial CSS Tutorial HTML Tutorial About Us

Lesson 32: Creating Graphics Part 2


In the previous lesson, you have learned how to write JavaScript code to draw straight lines on a canvas. In this lesson, we shall learn more advanced skills in creating graphics using JavaScript.

32.1 Drawing a Rectangle with Solid Color

We can draw a rectangle and fill it with a certain color using the fillRect() method. The default color is black. The fillRect() method contains four parameters, as follows:

fillRect(x,y,w,h)
x= The x-coordinate of the upper-left corner of the rectangle
y= the y-coordinate of the upper-left corner of the rectangle
w=the width  of the rectangle,(in pixels)
h=The height of the rectangle(in pixels)

The following script draws a rectangle with black color.

<canvas id="myCanvas" width="300" height="150" style="border:1px solid #d3d3d3;">
</canvas><br><br>
<input type="button" Value="Draw Rectangle" Onclick="DrawRect()">

<script>

function DrawRect()
{
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
ctx.fillRect(20,20,150,100);
}

</script>
The Output


To fill the rectangle with a different color, use the fillStyle property, as follows:

ctx.fillStyle =color
The following script will fill the rectangle with blue color.
<script>

function DrawRect1()
{
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");

ctx.fillStyle ="blue"
ctx.fillRect(20,20,150,100);
}

</script>
The Output


32.2 Drawing a Rectangle with Color in Gradient

We use the createLinearGradient() method creates a linear gradient style to fill an object such as a rectangle. It can also be used for other objects such as circles, lines, and text.

The createLinearGradient() method comprises four parameters:

createLinearGradient(x1,y1,x2,y2)
x1=the x-coordinate of the start point of the gradient
y1=the y-coordinate of the start point of the gradient
x2=the x-coordinate of the end point of the gradient
y2=the y-coordinate of the end point of the gradient

Further, we need to use addColorStop() method to specify different colors, and where to position the colors in the gradient object.

The following function draws a rectangle and creates a gradient comprises the blue and cyan color.

function DrawRect()
{
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
var my_gradient=ctx.createLinearGradient(0,0,0,170);
my_gradient.addColorStop(0,"blue");
my_gradient.addColorStop(1,"cyan");
ctx.fillStyle=my_gradient;
ctx.fillRect(20,20,150,100);
}
The Output



❮ Previous Lesson Next Lesson ❯


Copyright©2008 Dr.Liew Voon Kiong. All rights reserved |Contact|Privacy Policy