3

I'm looking into generating a line on an HTML canvas composed of several different coloured line segments with the data derived from JSON. I came across this post here: how draw in canvas read a json? I have managed to create a sample generates the line but the line segments don't retain their intended colour. The colour of the entire line is dictated by the colour of the final line segment (red).

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Train Control</title>
    <style>
        #canvas {border:1px solid black;}
    </style>
</head>
<body>
    <canvas id="canvas" width="600" height="200"></canvas>
    <script>
        function initCanvas(){
            var ctx = document.getElementById("canvas").getContext("2d");
            var json = [
                {"x":"200", "y":"100", "color": "blue"},
                {"x":"250", "y":"50", "color": "black"},
                {"x":"350", "y":"50", "color": "yellow"},
                {"x":"400", "y":"100", "color": "purple"},
                {"x":"500", "y":"100", "color": "red"}
            ]
            ctx.beginPath();
            ctx.moveTo(100,100);

            for(var i=0; i < json.length; i++){
                ctx.lineTo(json[i].x, json[i].y);
                ctx.strokeStyle = json[i].color;
                ctx.stroke();
            }

        }
        initCanvas()
    </script>
</body>

I have stepped through the code using Chrome's developer tools and each line segment shows the correct colour but it changes when the next segment is created. This occurs whether I use colours by name or the hex equivalent. Is it possible to do what I want or is this just impossible using lines on HTML canvas? If so, how can I do what I'd like to do?

Thank you for your time and advice.

nicodemus
  • 33
  • 5
  • You should invoke ctx.beginPath(); at the end of the for cycle. In order to apply different colors, you have to use multiple paths. – GrafiCode Mar 18 '19 at 22:45

1 Answers1

1

As I was saying in my comment, you should invoke ctx.beginPath(); at the end of the for cycle. In order to apply different colors, you have to use multiple paths.

.
.
.

for(var i=0; i < json.length; i++){
   ctx.lineTo(json[i].x, json[i].y);
   ctx.strokeStyle = json[i].color;
   ctx.stroke();
   ctx.beginPath();
}
GrafiCode
  • 1,698
  • 2
  • 22
  • 21
  • Thank you for the recommendation. I have made the change that you suggested but it doesn't work to create the multi-coloured line, when I opened the file directly into Chrome, Firefox or Internet Explorer. I wondered if it related to my not using a web server so I loaded the file there and accessed it using Chrome, FF and IE again. In every case, only the first segment (the horizontal blue line) is created. Stepping through the code using developer tools shows only this segment and there are no errors in the console. Any other suggestions? – nicodemus Mar 19 '19 at 14:08