javascript – HTML5 Canvas:渐变和strokeStyle让我感到困惑

为什么以下代码不会产生三条线,所有线都具有相似的渐变?

<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().事实证明,线条是路径的一部分,因此如果您没有开始新的路径,它会认为您仍在继续旧路径,因此使用您的原始起点和最终终点作为开始和结束用于渐变目的.

相关文章

kindeditor4.x代码高亮功能默认使用的是prettify插件,prett...
这一篇我将介绍如何让kindeditor4.x整合SyntaxHighlighter代...
js如何实现弹出form提交表单?(图文+视频)
js怎么获取复选框选中的值
js如何实现倒计时跳转页面
如何用js控制图片放大缩小