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:

        <canvas id="myCanvas" style="">

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%; }
	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
	// "center" text
	context.font = "40pt Calibri";
	context.fillStyle = "#0000ff"; // text color
	var text = "(" + event.pageX + ", " + event.pageY + ")";
	var metrics = context.measureText(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.


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: Logo

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

Google+ photo

You are commenting using your Google+ 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 )


Connecting to %s

%d bloggers like this: