Javascript 在HTML5画布中绘制虚线的性能较慢
我正在尝试使用HTML5画布制作一个Pong克隆。我想在球场中间画一条虚线,就像原来的乒乓球一样。为此,我扩展了Javascript 在HTML5画布中绘制虚线的性能较慢,javascript,performance,html5-canvas,Javascript,Performance,Html5 Canvas,我正在尝试使用HTML5画布制作一个Pong克隆。我想在球场中间画一条虚线,就像原来的乒乓球一样。为此,我扩展了canvasrendingcontext2d对象,如优秀书籍中所示: CanvasRenderingContext2D.prototype.dashedLine = function (x1, y1, x2, y2, dashLength) { dashLength = dashLength === undefined ? 5 : dashLength; var de
canvasrendingcontext2d
对象,如优秀书籍中所示:
CanvasRenderingContext2D.prototype.dashedLine = function (x1, y1, x2, y2, dashLength) {
dashLength = dashLength === undefined ? 5 : dashLength;
var deltaX = x2 - x1;
var deltaY = y2 - y1;
var numDashes = Math.floor(
Math.sqrt(deltaX * deltaX + deltaY * deltaY) / dashLength);
for (var i=0; i < numDashes; ++i) {
context[ i % 2 === 0 ? 'moveTo' : 'lineTo' ]
(x1 + (deltaX / numDashes) * i, y1 + (deltaY / numDashes) * i);
}
最后,我有一个名为animLoop()
的函数,它实际调用render()
函数,并利用requestAnimationFrame()
实现更平滑的动画:
function animLoop() {
render();
requestAnimationFrame(animLoop);
}
window.requestAnimationFrame = (function() {
return (
window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
function( callback ){
window.setTimeout(callback, 1000 / 60);
}
);
})();
如果我让我的游戏运行超过30秒,它就会开始急剧减速,以至于无法运行,Firefox和Chrome浏览器的CPU使用率都会徘徊在134%左右。慢度仅在渲染虚线时出现。我不确定发生了什么,但在下面我还通过Chrome Inspectors profiler运行了我的代码,并获得以下信息:
我的renderBackground()
函数只占用了.46%的CPU时间。另外,我不确定(程序)
应该表示什么。有没有想过是什么原因导致了这种缓慢
此外,您还可以在我的上查看到目前为止的完整代码。每次调用
ctx时,您都会在默认路径上累积对lineTo的所有调用。dashedLine
,并且自应用程序启动以来,调用笔划将笔划路径中的所有行。因为您正在运行动画,所以当调用每个帧的笔划时,路径将很快有很多线要绘制
在ctx.dashedLine
之前添加ctx.beginPath()
以解决此问题
function renderBackground() {
ctx.lineWidth = 5;
ctx.strokeStyle = '#FFFFFF';
ctx.fillStyle = '#000000';
ctx.fillRect(0, 0, cWidth, cHeight);
ctx.beginPath(); // <-- add it here
ctx.dashedLine(0, 0, 0, cHeight, 10);
ctx.stroke();
}
函数renderBackground(){
ctx.lineWidth=5;
ctx.strokeStyle='#FFFFFF';
ctx.fillStyle='#000000';
ctx.fillRect(0,0,cWidth,cHeight);
ctx.beginPath();//看起来您正在累积默认路径上对lineTo的所有调用。请尝试在ctx.dashedLine
之前放置ctx.beginPath()
。就是这样。忘记了beginPath()
。谢谢!
function renderBackground() {
ctx.lineWidth = 5;
ctx.strokeStyle = '#FFFFFF';
ctx.fillStyle = '#000000';
ctx.fillRect(0, 0, cWidth, cHeight);
ctx.beginPath(); // <-- add it here
ctx.dashedLine(0, 0, 0, cHeight, 10);
ctx.stroke();
}