Friday, August 31, 2012

HTML5 Canvas, fill background

In the example, the function resetCanvas() will fill background according to canvas size. Also, bind the "resize" event to resetCanvas() function using jQuery, such that when user re-size the window, the background always follow to new window size.

HTML5 Canvas, fill background


<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Mobile-Web-App: HTML5 Canvas</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.0.min.js"></script>
<script type="text/javascript">

var canvas;
var context; 

$(window).bind("resize", resetCanvas);

function loadcanvas(){
 window.scrollTo(0, 1);
 resetCanvas();
}

function drawBackground(){

 context.fillStyle = "#505050";
 context.fillRect(0, 0, canvas.width, canvas.height);
 
}

function resetCanvas(){
 canvas = document.getElementById("mycanvas");

 canvas.width = window.innerWidth;
 canvas.height = window.innerHeight; 
 
 context = canvas.getContext("2d");
 
 drawBackground();
}

</script>
</head>
<body onload="loadcanvas();">

<canvas id="mycanvas">
Sorry! Your browser doesn't support Canvas.
</canvas>
</body>
</html>

No comments:

Post a Comment