My code generates imagedata and places it in a canvas. However, when I expand the window size, the rendering slows down significantly.
Is there a way to optimize this for smooth operation in fullscreen mode, even though it might seem naive?
What would be the most effective approach to optimizing it?
You can view the running code here.
This is the structure of my code:
HTML:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8>
<title>_#Example</title>
<meta name="description" content="_#Example">
<meta name="author" content="SitePoint">
<link rel="stylesheet" href="css/main.css?v=1.0">
<!--[if lt IE 9]>
<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
</head>
<body>
<script src="js/main.js"></script>
<div id="containingDiv">
<canvas class = "board" id = "mainBoard">Your browser version is not supported</canvas>
</div>
</body>
</html>
CSS:
#containingDiv {
overflow: hidden;
}
#mainBoard {
position: absolute;
top: 0px;
left: 0px;
}
JS:
var canvas, ctx, frame;
function initAll(){
canvas = document.getElementById('mainBoard');
buffer = document.createElement('canvas');
ctx = canvas.getContext('2d');
frame = ctx.createImageData(ctx.canvas.height,ctx.canvas.width);
};
function resizeCanvas() {
ctx.canvas.width = window.innerWidth;
ctx.canvas.height = window.innerHeight;
};
function draw(){
frame = ctx.createImageData(ctx.canvas.width, ctx.canvas.height);
for(var i=0;i<ctx.canvas.height; i++){
for(var j=0; j<ctx.canvas.width; j++){
var index = ((ctx.canvas.width * i) + j) * 4;
frame.data[index]= 255*Math.random();
frame.data[index + 1]=255*Math.random();
frame.data[index + 2]=255*Math.random();
frame.data[index + 3]=255;
}
}
ctx.putImageData(frame, 0, 0 );
};
window.requestAnimFrame = (function(callback) {
return window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function(callback) {
window.setTimeout(callback, 2000);
};
})();
function animate() {
draw();
requestAnimFrame(function() {
animate();
});
};
function viewDidLoad(){
initAll();
resizeCanvas();
animate();
};
window.onload = viewDidLoad;
window.onresize = resizeCanvas;