Monday, March 11, 2013

Canvas | Square or Rectangle Example

In HTML5, there are tools using them we can draw different shapes like square, rectangle, triangle and circles. I would first start with Square and rectangle shapes. below example will show you how to draw square and rectangle on Canvas and apply color to shape border.

Code:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Canvas Example</title>
</head>
<body>
<canvas id="canvas" width="500px" height="500px"></canvas>
</body>

<script>
var oCanvas = document.getElementById("canvas"); //retrieved element of Canvas
var oContext = oCanvas.getContext("2d"); //get context of canvas to apply drawings.


oContext.strokeStyle = "#ff0000";  //color of border, applied Red color
oContext.lineWidth = 1; // width of the border
oContext.strokeRect (100,100,100,100); // strokeRect function draws square without filling color. parameters are x,y, width, height
oContext.strokeStyle = "#00ff00";  //color of border, applied Green color
oContext.strokeRect (100,250, 200,100); //will draw horizontal rectangle
oContext.strokeStyle = "#0000ff";  //color of border, applied Blue color
oContext.strokeRect (350,100, 100,200); //will draw horizontal rectangle


</script>
</html>

Above example shows square and rectangle shapes. now i will show you how to apply shadow to shapes.


<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Canvas Example</title>
</head>
<body>
<canvas id="canvas" width="500px" height="500px"></canvas>
</body>

<script>
var oCanvas = document.getElementById("canvas"); //retrieved element of Canvas
var oContext = oCanvas.getContext("2d"); //get context of canvas to apply drawings.


oContext.strokeStyle = "#ff0000";  //color of border, applied Red color
oContext.lineWidth = 1; // width of the border
oContext.shadowOffsetX = 10; // X offset
oContext.shadowOffsetY = 10; // Y offset
oContext.shadowColor = "rgba(255,0,0,.4)"; // parameters of rgba function are Red, Green, blue and level of Opacity
oContext.shadowBlur = 10; // at what level, shadow to be blurred.
oContext.strokeRect (100,100,100,100); // strokeRect function draws square without filling color. parameters are x,y, width, height
</script>
</html>





No comments:

Post a Comment