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; }
).

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.

Last updated by at .
Back to top