【发布时间】:2014-03-24 22:43:37
【问题描述】:
对于这个项目http://biduleohm.free.fr/ledohm/(对不起,用户界面是法语,但代码是英语)我需要一个角度渐变,但它在本机中不存在,所以我使用线性渐变实现了它线,我画的线越来越长,形成一个三角形。结果在图形上还可以,但速度不是很好(125 个三角形为 1850 毫秒)。它在 [Répartition] 选项卡中,如果其中一个输入上有 keyup 事件,它会重绘,不要害怕明显的缓慢,我限制为每 2000 毫秒最多重绘一次。
之前我在整个三角形上使用了简单的线性渐变(但这与现实不符)并且速度还可以,不到一秒就可以绘制出数千个三角形。使用了这个函数:
drawFrontLightForColor : function(x, y, w, h, color) {
var x2 = x - w;
var x3 = x + w;
var gradient = Distri.frontCanvas.createLinearGradient(x2, y, x3, y);
gradient.addColorStop(0, 'rgba(' + color + ', ' + Distri.lightEdgeAlpha + ')');
gradient.addColorStop(0.5, 'rgba(' + color + ', ' + (color == Distri.lightColors.cw ? Distri.lightCenterAlphaCw : Distri.lightCenterAlphaOther) + ')');
gradient.addColorStop(1, 'rgba(' + color + ', ' + Distri.lightEdgeAlpha + ')');
Distri.frontCanvas.fillStyle = gradient;
Distri.frontCanvas.beginPath();
Distri.frontCanvas.moveTo(x, y);
Distri.frontCanvas.lineTo(x2, (y + h));
Distri.frontCanvas.lineTo(x3, (y + h));
Distri.frontCanvas.lineTo(x, y);
Distri.frontCanvas.fill();
Distri.frontCanvas.closePath();
},
然后我切换到这个功能:
drawFrontLightForColor : function(x, y, w, h, centerColor, edgeColor) {
var ratio = w / h;
var tmpY;
var tmpW;
var x2;
var x3;
var gradient;
Distri.frontCanvas.lineWidth = 1;
for (var tmpH = 0; tmpH < h; tmpH++) {
tmpY = y + tmpH;
tmpW = Math.round(tmpH * ratio);
x2 = x - tmpW;
x3 = x + tmpW;
gradient = Distri.frontCanvas.createLinearGradient(x2, tmpY, x3, tmpY);
gradient.addColorStop(0, edgeColor);
gradient.addColorStop(0.5, centerColor);
gradient.addColorStop(1, edgeColor);
Distri.frontCanvas.beginPath();
Distri.frontCanvas.moveTo(x2, tmpY);
Distri.frontCanvas.lineTo(x, tmpY);
Distri.frontCanvas.lineTo(x3, tmpY);
Distri.frontCanvas.strokeStyle = gradient;
Distri.frontCanvas.stroke();
Distri.frontCanvas.closePath();
}
},
你可以找到整个源码here
我不能将 beginPath、stroke、closePath 放在循环之外,因为每次迭代都会改变渐变(我已经尝试过,但它对每一行都使用了最后一个渐变(具有讽刺意味的是,它与第一个功能...)这是可以理解的,但不是我想要的)。
我接受任何建议(包括重做整个函数并修改他的调用者以外包一些代码)以提高速度,比如说 5 倍(最好是更多)。
【问题讨论】:
-
你可以试试
WebGL。它应该能够处理数百万个三角形。 -
我没有在您的链接上找到“重新分区”选项卡。您能否将 .png 附加到您的问题中。
-
是的,但如果可能的话,我想保留画布。在我看来,WebGL 似乎与所有浏览器都不兼容,但我会检查一下,谢谢。 @markE 我不能发布超过 2 个链接,因为这是我的第一个问题。但是执行 Shared.$tabs._1.click();在控制台中。
-
嗯,WebGL 似乎比我想象的更有吸引力,3D 和交互性为我的项目提供了无限的可能性......并且所有最近的浏览器都支持它。谢谢推荐,我试试。但只是出于好奇,是否可以显着优化我的代码?
标签: javascript optimization canvas gradient