我需要使用json数据绘制线性图。我只允许使用HTML,CSS和JavaScript。不允许使用任何库和api。谁能帮我解决这个问题。提前致谢。
json数据:
var marks: [
{
"name": AAA,
"age":20,
"exam": {
"no_of_exams": 5,
"average": "400"
}
},
{
"name": BBB,
"age":25,
"exam": {
"no_of_exams": 10,
"average": "800"
}
},{
"name": ccc,
"age":30,
"exam": {
"no_of_exams": 8,
"average": "700"
}
}
];
现在,我需要绘制no_of_exams和平均值。
最佳答案
首先,您需要创建html <canvas>
元素,在其中绘制图形。然后,您可以使用document.getElementById
或document.querySelector
通过id,class或其他方式获取元素。然后,您可以通过编程方式绘制一个简单的形状,如下所示:
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
ctx.fillStyle = "#FF0000";
ctx.fillRect(10,0,20,75); // fillRect(x,y,width,height)
从JSON文件传递数据,您可以使矩形填充所需的高度和颜色。剩下的全部-循环遍历所有数据并进行一些调整。像这样
var colors = ['red','green','blue','purple']
for (let i=0; i<marks.length; i++) {
ctx.fillStyle = colors[i]
ctx.fillRect(marks[i].exam.no_of_exams,marks[i].exam.average,20,75);
}
您可以参考W3Schools docs以获得有关使用画布的更多信息。
关于javascript - 如何在没有任何库的情况下使用HTML,CSS,JavaScript中的json数据绘制图形,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/45582686/