基本上我有一些代碼可以生成一個imagedata並將其放入畫布中。如何提高我的畫布動畫速度?
但是,當我放大窗口時,渲染會顯着減慢。
反正有沒有優化這個在全屏運行平穩? (天真我知道)
什麼是優化它的最佳方法?
下面是代碼運行:http://jsfiddle.net/AMwNc/3/
這裏是我的代碼:
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;
我剛剛做到了。 –