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.