1

基本上我有一些代碼可以生成一個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; 
+0

我剛剛做到了。 –

回答

3

大多數HTML5畫布實現方式真的會從使用GPU硬件加速的高級操作函數(如drawImage或描邊路徑)中受益匪淺。不幸的是,對原始圖像數據的任何操作都不是硬件加速的。用於生成隨機像素數據的算法在CPU上執行,而不是在GPU上執行,因此速度很慢。

當您想要進行大規模的像素級操作並仍然保持高性能時,您可能需要查看WebGL和像素着色器。這將允許您在GPU上實現像素級算法,其速度可以提高几個數量級。

+0

我喜歡這個想法。我會看看它。謝謝。 –

0

我看到你調用initAll()

frame = ctx.createImageData(ctx.canvas.height,ctx.canvas.width); 

2倍,並繪製()。您在調整畫布大小之前創建imageData。 而我不知道在動畫()你處理畫畫布。

我的建議:您應該刪除initAll()中的那個調用。希望它有幫助