为什么以下代码不会产生三条线,所有线都具有相似的渐变?
<html> <body style="background: black;"> <canvas id="Test" width="516" height="404"> </canvas> <script> var ctx = document.getElementById('Test').getContext('2d'); ctx.lineWidth = 8; function addColorStops(gradient) { gradient.addColorStop(0.5,'rgba(151,165,193,0.5)'); gradient.addColorStop(1,1)'); } function drawLine(x1,x2,y) { var g = ctx.createLinearGradient(x1,y,y); addColorStops(g); ctx.strokeStyle = g; ctx.moveTo(x1,y); ctx.lineTo(x2,y); ctx.stroke(); } drawLine(10,100,10); drawLine(10,30); drawLine(10,50); </script> </body> </html>
相反,第一行获得非常非常轻微的渐变,第二行获得非常好的渐变,最后一行得到一个剧烈的渐变.
我认为这源于对createLinearGradient的参数应该如何工作的误解,或者误解了strokeStyle赋值如何影响未来的笔画……
解决方法
唉,我明白了.我需要在ctx.strokeStyle = g;之前添加一个ctx.beginPath().事实证明,线条是路径的一部分,因此如果您没有开始新的路径,它会认为您仍在继续旧路径,因此使用您的原始起点和最终终点作为开始和结束用于渐变目的.