我的游戏有很多激光物体。mx和my代表速度。我使用下面的代码从激光器后面的2个像素到激光器前面2个像素的方向绘制一条线。
删除函数的第一行将分析的百分比调整了约1%,但我不喜欢它的外观。我认为我可以通过按行宽排序来优化绘图,但这似乎对我没有太大帮助。
我还能怎么优化它呢?
Laser.prototype.draw = function(client, context) {
context.lineWidth = Laser.lineWidth;
context.beginPath();
context.moveTo(this.x - this.mx * 2, this.y - this.my * 2);
context.lineTo(this.x + this.mx * 2, this.y + this.my * 2);
context.strokeStyle = this.teamColor;
context.closePath();
context.stroke();
}发布于 2016-07-04 12:00:53
与其将事物乘以2,为什么不将它们相加呢?例如。
context.moveTo(this.x - this.mx - this.mx, this.y - this.my - this.my);
context.lineTo(this.x + this.mx + this.mx, this.y + this.my - this.my);测试表明,在imac上,加法运算比乘法运算快一个数量级
发布于 2016-07-04 14:57:06
不要使用moveTo或lineTo,因为它们不使用硬件来渲染,并且非常慢。此外,您的代码还绘制了两次这条线
ctx.beginPath(); // starts a new path
ctx.moveTo(x,y); // sets the start point of a line
ctx.lineTo(xx,yy); // add a line from x,y to xx,yy
// Not needed
ctx.closePath(); // This is not like beginPath
// it is like lineTo and tells the context
// to add a line from the last point xx,yy
// back to the last moveTo which is x,y这将使本已缓慢的渲染时间减半。
一种使用位图绘制线条的快速方法。
首先,首先创建一个图像来保存用于绘制直线的位图
function createLineSprite(col,width){
var lineSprite = document.createElement("canvas");
var lineSprite.width = 2;
var lineSprite.height = width;
lineSprite.ctx = lineSprite.getContext("2d");
lineSprite.ctx.fillStyle = col;
lineSprite.ctx.fillRect(0,0,2,width);
return lineSprite;
}
var line = createLineSprite("red",4); // create a 4 pixel wide red line sprite或者,您可以使用您加载的图像。
要绘制一条线,您只需创建一个指向该线方向的变换,并绘制该线长度的精灵。
// draw a line with sprite from x,y,xx,yy
var drawLineSprite = function(sprite,x,y,xx,yy){
var nx = xx-x; // get the vector between the points
var ny = yy-y;
if(nx === 0 && ny === 0){ // nothing to draw
return;
}
var d = Math.hypot(nx,ny); // get the distance. Note IE does not have hypot Edge does
// normalise the vector
nx /= d;
ny /= d;
ctx.setTransform(nx,ny,-ny,nx,x,y); // create the transform with x axis
// along the line and origin at line start x,y
ctx.drawImage(sprite, 0, 0, sprite.width, sprite.height, 0, -sprite.height / 2, d, sprite.height);
}要画出这条线
drawSpriteLine(line,0,0,100,100);当您绘制完所有线条后,您可以使用以下命令重新获得默认转换
ctx.setTransform(1,0,0,1,0,0);精灵可以是任何东西,这允许非常详细的线条和很好的游戏激光和类似的。
如果你有许多不同的颜色要绘制,然后创建一个有许多颜色的精灵(图像),然后在线绘制功能中只绘制具有你想要的颜色的精灵的一部分。您可以将单个像素拉伸到任意大小,以便在小位图上获得多种颜色。
https://stackoverflow.com/questions/38176561
复制相似问题