有没有简单的方法可以使用JavaScript将JSON数据分配给svg元素? [英] Is there any easy way to assign JSON data to svg element using Javascript?
问题描述
我是SVG的新手,正在尝试使用它创建一个简单的图形. 但是我不知道如何使用'for loop'分配JSON数据在SVG中动态绘制矩形.帮助我获得1个循环并分配每个值以绘制要附加到SVG元素的矩形.
I am new to SVG, and trying to create a simple graph using it. But I don't know how assign JSON data to draw a rectangle in SVG dynamically using 'for loop'.Help me to get 1 loop and assigning each value to draw rectangle that I want to append to SVG element.
<script src="http://d3js.org/d3.v3.min.js"></script>
<script>
window.onload = function(){
var data = [
{
"srno" : 1 ,
"status" : "production" ,
"duration" : 30,
"color" : "#00ff00",
},
{
"srno" : 2 ,
"status" : "idle" ,
"duration" : 5 ,
"color" : "#ff0000"}];
//Make an SVG Container
var svgContainer = d3.select("body").append("svg")
.attr("width", 720)
.attr("height", 50);
//Draw the Rectangle
var rectangle = svgContainer.append("rect")
.attr("x", 0)
.attr("y", 0)
.attr("width", machines [1].duration)
.attr("height", 50)
.attr("fill","green");//Here I want the color from JSON object
//And I want duration to be the width property,
//Status be the tooltip , which is not working
</script>
推荐答案
这是一个很好的文章,您可以在其中学习如何做:
Here is a good article where you can learn on how to do that:
http://tympanus.net/codrops/2013/11/05/animated-svg-icons-with-snap-svg/
您可以下载源文件,在"js"目录中,您将使用svg数据找到一个json文件.
You can download the source files, within the "js" directory you will find a json file using svg data.
您可以考虑使用 Snap.svg ,可以为您提供很多帮助:
You might consider use Snap.svg, could help you a lot:
希望它对您有帮助!
这篇关于有没有简单的方法可以使用JavaScript将JSON数据分配给svg元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!