The CANVAS Element in
HTML5 is a great solution for graphical representation. We're just going to
learn how to use the CANVAS Element in HTML5. The CANVAS Element is incomplete
without the JavaScript. Let's understand it with an example. Think of a page of
your drawing book, we're going to draw some shapes on it. So here the page is
the CANVAS and the drawing you make is the JavaScript (just example). So if the
size of your shapes will be greater than the page, what will happen? The
portion of the drawing that is outside the page's edges will not be visible.
Same is true for the CANVAS. If the size of the shapes is greater than the size
of the canvas then the portion of the shapes that are outside the canvas will
not be visible.
OK now it lets see
where to put the codes.
<!DOCTYPE html>
<html>
<head>
<title>CANVAS</title>
</head>
<body>
<canvas width="500" height="500" id="addskills"/></canvas>
<script>
var canvas= document.getElementById("addskills");
var rit= canvas.getContext("2d");
</script>
</body>
</html>
<head>
<title>CANVAS</title>
</head>
<body>
<canvas width="500" height="500" id="addskills"/></canvas>
<script>
var canvas= document.getElementById("addskills");
var rit= canvas.getContext("2d");
</script>
</body>
</html>
Here in the
<body> we put the JavaScript. First of all, we declared the
variable for the canvas and a method (getElementByID) to select our canvas.
Then we declared the second variable (rit) and used the getContext method
to select the Context. Then we closed the script and then placed the canvas
inside the body.
Now all we have to do
is to move ahead and draw something.
Let’s draw a
rectangle. To do so we have to first begin the path, then set the color and
then declare the height and width.
See the example.
<!DOCTYPE html><html>
<head>
<title>CANVAS</title>
</head>
<body>
<p>
<font size="20" color=”skyblue” face=”century gothic”> Your rectangle!</font>
</p>
<p>
<canvas width="500" height="500" id="addskills"/></canvas>
<script>
var canvas= document.getElementById("addskills");
var rit= canvas.getContext("2d");
rit.beginPath();
rit.fillStyle = "lightblue";
rit.fillRect(0, 0, 500, 500); // x axis, y axis, width, height
</script>
</p>
</body>
</html>
Output
OK now let’s move one
step ahead. Let’s draw a Circle.
To draw a circle we
have to declare the x and y axis, radius, start angle and stop angle.
It looks like this: arc(100,
60, 30, 0, 360, true);
So let’s start coding.
<!DOCTYPE html><html>
<head>
<title>CANVAS</title>
</head>
<body>
<p>
<font size="20" color=”skyblue” face=”century gothic”> Your Circle!</font>
</p>
<p>
<canvas width="300" height="300" id="addskills"/></canvas>
<script>
var canvas= document.getElementById("addskills");
var rit= canvas.getContext("2d");
rit.beginPath();
rit.arc(100, 60, 50, 25, 360,true);
rit.fillStyle = "lightgreen";
rit.fill();
rit.beginPath();
rit.arc(100, 60, 30, 0, 360,true);
rit.fillStyle = "yellow";
rit.fill();
</script>
</p>
</body>
</html>
Output:
0 comments:
Post a Comment