设置从JSON生成的HTML画布线段的颜色

时间:2019-03-18 22:40:10

标签: javascript json canvas

我正在研究在HTML画布上生成一条线,该线由几个不同颜色的线段组成,并带有从JSON导出的数据。我在这里碰到过这篇文章:how draw in canvas read a json?我设法创建了一个示例来生成线条,但是这些线段没有保留其预期的颜色。整行的颜色由最后一条线段的颜色(红色)决定。

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

我已经使用Chrome的开发人员工具逐步完成了代码,每个线段均显示正确的颜色,但是在创建下一个线段时它会更改。无论是按名称使用颜色还是使用十六进制等效颜色,都会发生这种情况。是否有可能做我想做的事,或者使用HTML画布上的行只能做到这一点?如果是这样,我该怎么做?

感谢您的时间和建议。

1 个答案:

答案 0 :(得分:1)

正如我在评论中所说,您应该调用ctx.beginPath();在for循环的末尾。为了应用不同的颜色,您必须使用多个路径。

<p style="font-size: 11pt;font-family: Times;">December 28, 2018</p>
    <p style="font-size: 11pt;font-family: Times;">Dear Lisa,</p>
    <p style="font-size: 11pt;font-family: Times;"> I would love to grab coffee with you!<br clear="none">When does that work? </p><p style="font-size: 11pt;font-family: Times;">Best Regards,</p>