Tuesday, 25 April 2017

Testing to see Whether the Browser Supports Canvas in HTML5



We have a reference to the canvas element on the HTML page, we need to test to see whether it contains a context. The Canvas context refers to the drawing surface defined by a web browser to support Canvas. Simply put, if the context does not exist, neither does the Canvas
There are several ways to test this:
First :
if(!thecanvas || !thecanvas.getContext)
{
Return;
}
This tests two things.
First, it test to see whether thecanvas does not contain false (the value returned by document.getElementById() if the named id does not exist). Then it tests whether the getContext() function exists.
The return statement breaks out and stops execution if the test fails.
Second:
Uses a function with a test of dummy canvas created for the sole purpose of seeing whether browser support exists:
function canvasSupport()
{
return !! document.createElement(‘canvas’).getContext;
}
function canvasApp()
{
if(!canvasSupport)
{
return;
}}
Third :
To use the modernizr.js library Modernizr – an easy-to-use lightweight library for testing support for various web beads technologies create a set of static Boolean that you can test against to see whether canvas is supported.
To include modernizr.js in your HTML page download the code from http://www.modernizr.com/ and then include the external .js file in your HTML page.
<script src=”modernizr.js”></script>
To test for canvas change the canvasSupport() function to look like this:
function canvasSupport()
 {
return Modernizr.canvas ;
}
2D Context:
     var context=theCanvas.getContext("2d");

The drawScreen() function:
                                        The first thing we want to do is clear the drawing area. The following two lines of code draw a yellow box on the screen that is same size as the canvas. fillStyle() sets the color, and fillRect() create a rectangle and puts it on the screen:

context.fillStyle="#ffffaa";
context.fillRect(0,0,500,300);

First we set the color of the text in the same way that we set the color of the rectangle:
context.fillStyle="#000000";
Then we set the font size and weight:
context.font="20px sans-serif";
Next we set the vertical alignment of the font:
context.textBaseline="top";
finally we print our text on the screen by calling the fillText() method pf the context object. The three parameters of this method are text string, x position, and y position.
context.fillText("Hello World !", 195, 80);

No comments:

Post a Comment