HTML5画布:渐变和strokeStyle让我感到困惑。

3
为什么下面的代码不能生成三条具有类似渐变的线?
<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, 'rgba(151, 165, 193, 1)');
        }

        function drawLine(x1, x2, y) {
            var g = ctx.createLinearGradient(x1, y, x2, y);
            addColorStops(g);
            ctx.strokeStyle = g;

            ctx.moveTo(x1, y);
            ctx.lineTo(x2, y);
            ctx.stroke();
        }

        drawLine(10, 100, 10);
        drawLine(10, 100, 30);
        drawLine(10, 100, 50);
        </script>
  </body>
</html>

相反,第一行获得了非常微弱的渐变,第二行获得了相当不错的渐变,而最后一行则获得了极端的渐变。

我认为这源于对createLinearGradient参数应该如何工作或误解strokeStyle分配如何影响未来笔画的误解...

2个回答

6

啊,我弄懂了。在 ctx.strokeStyle = g; 之前需要添加 ctx.beginPath()。因为线条是路径的一部分,如果不开始新路径,它会认为你仍在继续旧路径,并使用原始起点和最终终点作为渐变的起点和终点。


1

我发现strokeStyle被覆盖了!通过添加beginPath,我的描边颜色可以正常工作。

ctx.beginPath(); ctx.moveTo( x, y ); ctx.lineTo( x, y ); ctx.strokeStyle = "#182945"; ctx.stroke();

谢谢。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接