Sunday, January 29, 2012

How to draw a rectangle and give color in html5

How to draw the only built-in shape provided by the HTML5 canvas API, a rectangle. As unexciting as a rectangle might seem, many applications use them in one way or another, so you might as well get acquainted.
Follow these steps to draw a simple rectangle centered on the canvas:
1.Define a 2D canvas context:
window.onload = function(){
var canvas = document.getElementById("myCanvas");
var context = canvas.getContext("2d");
 
2.;Draw a rectangle using the rect() method, set the color fill with the fillStyle property, and then fill the shape with the fill() method:
context.rect(canvas.width / 2 - 100, canvas.height / 2 - 50, 200, 100);
context.fillStyle = "#8ED6FF";
context.fill();
context.lineWidth = 5;
context.strokeStyle = "black";
context.stroke();
};
.3. Embed the canvas tag inside the
body of the HTML document:


4. As you can see from the preceding code, we can draw a simple rectangle by using the rect() method:
context.rect(x,y,width,height);

0 comments: