基本上我有一些代码可以生成图像数据并将其放在 Canvas 中。
但是,当我放大窗口时,渲染速度会大大降低。
有没有办法优化这个以全屏流畅运行? (天真我知道)
优化它的最佳方法是什么?
这是运行的代码: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;
最佳答案
大多数 HTML5 canvas 实现确实受益于将 GPU 硬件加速用于高级操作功能,如 drawImage 或描边路径。不幸的是,对原始图像数据的任何操作都不是硬件加速的。您生成随机像素数据的算法是在 CPU 上执行的,而不是在 GPU 上执行的,因此它非常慢。
如果您想进行大规模像素级操作并仍保持其性能,您可能需要了解一下 WebGL 和像素着色器。这将使您能够在 GPU 上实现像素级算法,速度会快几个数量级。
关于javascript - 如何提高我的 Canvas 动画速度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21344341/