Wednesday, March 13, 2013

Canvas | Text API

Canvas API is providing feature of displaying text on Canvas. There are two methods (1) fillText and strokeText. fillText method will fill up the text with specified color while StrokeText will only apply outline to text. by using both methods, we can display text with filled color and outline with different color.

Below example will demonstrate you that whatever text you will enter will be displayed in canvas with Red color. here i have applied shadow as well.

Enter the title you want to display on canvas in text field and then click on "Click me" button will draw text on canvas.


<!DOCTYPE html>
<html lang="en">
<meta charset="utf-8">
<title>Canvas | Text  Example</title>
<label for="txtTitle" id="lblTitle">Enter Title</label>
<input type="text" id="txtTitle" width="50"/>
<input type="button" id="btnOk" value="&nbsp;Click Me&nbsp;" onclick="fnClick()" />
<canvas id="canvas" width="500px" height="500px"></canvas>


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

var oTitle = document.getElementById("txtTitle").value; //get value of title entered by user
oContext.clearRect(0,0,500,500); //remove the content of canvas before drawing new text
oContext.font = "bold 60px tahoma"; //set font family, size and weight
oContext.fillStyle = "rgba(255,0,0,1)"; //set color to be filled
oContext.lineWidth = 2 ; //set border of the text
oContext.strokeStyle="rgba(0,0,0,1)"; //text outline color
oContext.shadowOffsetX = 10; //set shadowOffsetX
oContext.shadowOffsetY = 10; //set shadowOffsetY
oContext.ShadowBlur = 7; //blurness of shadow
oContext.shadowColor = "rgba(255,0,0,.5)"; //shadow color.
oContext.fillText(oTitle,100,100); //draw text at x-100 and y-100 location.
oContext.strokeText(oTitle,100,100); //draw outline text.

No comments:

Post a Comment