Game Development Reference
In-Depth Information
<script>
this.canvas = document.getElementById("canvasElement");
this.ctx = this.canvas.getContext('2d');
</script>
The canvas element has no drawing properties in itself and we use a script to draw
graphics. The getContext method returns the object, which provides methods to
draw text, lines, shapes, and graphics on the canvas.
The following code walks you through the methods of the 2D context object returned
from the getContext method:
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
ctx.fillStyle="#FF0000";
ctx.fillRect(0,0,10,10);
The fillstyle property will fill the rectangle with the red color. The following code
gets an image object and fills rect (0,0,100,100) with the image:
var img=document.getElementById("ball");
var patttern=ctx.createPattern(img,"repeat");
ctx.rect(0,0,100,100);
ctx.fillStyle=patttern;//fill pattern image
ctx.fill();
The following code sets fill color and text alignment and then draws the text at the
given coordinates, textX and textY . The ctx.measureText(txt).width function is
a text metrics function. It will give you the width of the text at the specified font style
and font size:
ctx.fillStyle = #FF0000; // This determines the text color, it can
take a hex value or rgba value (e.g. rgba(255,0,0,0.5))
ctx.textAlign = "center"; // This determines the alignment of
text, e.g. left, center, right
ctx.textBaseline = "middle";
ctx.font="14px Georgia";
var txt="My width";
ctx.fillText(txt+ctx.measureText(txt).width, textX, textY);
The following code introduces another powerful concept of transforms in the
drawing API. The ctx.transform() function sets the transformation matrix before
the next drawing API call:
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
ctx.fillStyle="green";
 
Search WWH ::




Custom Search