gpt4 book ai didi

javascript - 如何在上下文阴影 Canvas HTML5/Javascript 时提高性能?

转载 作者:行者123 更新时间:2023-11-30 10:33:04 24 4
gpt4 key购买 nike

我使用 Javascript 编写了一个 Windows 8 游戏 Metro 风格。当我将 gameContext 设置为阴影或透明时,我遇到了一个问题,导致游戏速度太慢。

ctx.shadowColor="black";
ctx.shadowBlur = 10;

ctx.globalCompositeOperation = "lighter";
ctx.globalAlpha = 0.3;

我怎样才能提高游戏的性能?

最佳答案

嗯……

不要使用阴影,因为它们是性能的敌人:http://www.html5rocks.com/en/tutorials/canvas/performance/

但是,您可以在不使用阴影的情况下获得带阴影的结果!

您可以通过将对象保存为缓存图像来显着加快绘制速度。下面是使用阴影绘制与绘制缓存图像的比较。使用缓存图像绘制比使用阴影绘制快数百倍

enter image description here

这是代码和 fiddle :http://jsfiddle.net/m1erickson/7YcaC/

<!DOCTYPE HTML>
<html>
<head>
<style>
body { margin: 0px; padding: 20px; }
canvas { border: 1px solid red; margin:10px; }
</style>
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
</head>
<body>
<p id="shadow">Redraw using shadows</p>
<canvas id="myCanvas1" width="220" height="120"></canvas><br/>
<p id="cache">Redraw using a cached image</p>
<canvas id="myCanvas2" width="220" height="120"></canvas>
<script>
var canvas1 = document.getElementById('myCanvas1');
var context1 = canvas1.getContext('2d');
var canvas2 = document.getElementById('myCanvas2');
var context2 = canvas2.getContext('2d');

// create a cache image of the shadowed rectangle
draw1();
var image=new Image();
image.src=canvas1.toDataURL();

var t1=new Date().getTime();
console.log(t1);
for(var i=0;i<100;i++){ draw1(); }
var t2=new Date().getTime();
console.log(t2);
for(var i=0;i<100;i++){ draw2(); }
var t3=new Date().getTime();
console.log(t3);
alert((t2-t1)+"/"+(t3-t2));
$("#shadow").text("Redraw using shadows took "+(t2-t1)+" ms");
$("#cache").text("Redraw using cached image took "+(t3-t2)+" ms");

function draw1(){
context1.clearRect(0,0,220,120);
canvas1.width=220;
canvas1.height=120;
context1.rect(10, 10, 200, 100);
context1.fillStyle = 'red';
context1.shadowColor = 'black';
context1.shadowBlur = 10;
context1.shadowOffsetX = 5;
context1.shadowOffsetY = 5;
context1.fill();
}

function draw2(){
context2.clearRect(0,0,220,120);
context2.drawImage(image,0,0);
}

</script>
</body>
</html>

关于javascript - 如何在上下文阴影 Canvas HTML5/Javascript 时提高性能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15706856/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com