HTML5 canvas: gradients and strokeStyle confuse me

Why doesn't the following code create three lines, all with the same gradients?

<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>

Instead of the first line, a very small gradient is obtained, the second line gets a pretty good gradient, and the last one gets a sharp gradient.

I think this is due to a lack of understanding of how parameters should work createLinearGradient, or a misunderstanding of how assignments strokeStyleaffect future touches ...

+3
source share
2 answers

, . ctx.beginPath() ctx.strokeStyle = g;. , , , , , , , , , .

+6

! startPath, .

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

+1

Source: https://habr.com/ru/post/1774873/


All Articles