HTML5 canvas full view

I just wanted to share this small code sample for embedding HTML5 canvas fully inside the browser window. The simplest HTML looks like this:

<!DOCTYPE HTML>
<html>
    <head>
    </head>
    <body>
        <canvas id="myCanvas" style="">
        </canvas>
    </body>
</html>

Add the link to the latest version of jQuery and add the basic code for initializing canvas. We will set the background color for the canvas to black.

var canvas;
var context;
var height, width;

// refresh internal and canvas dimensions after resize
$(window).resize(function() {
	width = canvas.width = $(window).width();
	height = canvas.height = $(window).height();
});

$(function() {
	// create 2D canvas
	canvas = document.getElementById("myCanvas");
	context = canvas.getContext("2d");
	
	width = canvas.width = $(window).width();
	height = canvas.height = $(window).height();
});

In order to prevent the occurrence of the vertical and horizontal scrollbars, add the following style:

* {margin:0; padding:0;}
html, body { width:100%; height:100%; }
#myCanvas
{
	background-color: black;
	display: block;
}

The final result is simple black background (all this could to achieve something like body { background-color: black; } :P).

Let’s add something dynamic for a change. We will display the current mouse coordinates in the screen center.

$("#myCanvas").mousemove(function(event) {
	// clear screen
	context.clearRect(0,0,width,height);
	
	// "center" text
	context.font = "40pt Calibri";
	context.fillStyle = "#0000ff"; // text color
	
	var text = "(" + event.pageX + ", " + event.pageY + ")";
	var metrics = context.measureText(text);

	context.fillText(text,
		width / 2 - metrics.width / 2,
		height / 2 - 20);
});

The final result can be seen in the screenshot below. If you turn on full screen mode inside the browser, the canvas will correctly resize and fill the whole screen.

Advertisements

About programabilan

Profesionalni programer, amaterski programer...

Posted on January 31, 2012, in Development, Web and tagged , , . Bookmark the permalink. Leave a comment.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: