【问题标题】:Is there any easy way to assign JSON data to svg element using Javascript?是否有任何简单的方法可以使用 Javascript 将 JSON 数据分配给 svg 元素?
【发布时间】:2015-07-08 07:58:22
【问题描述】:

我是 SVG 新手,正在尝试使用它创建一个简单的图形。 但我不知道如何分配 JSON 数据以使用“for 循环”在 SVG 中动态绘制一个矩形。帮助我获得 1 个循环并分配每个值以绘制我想要附加到 SVG 元素的矩形。

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

【问题讨论】:

  • 你有一些你迄今为止尝试过的示例代码吗?这是家庭作业吗?
  • 您能否分享一些代码,因为它会告诉我们您遇到的确切位置。它还可以为其他人节省精力,因为他们不必从头开始。此外,将避免不相关的答案
  • 这是我正在练习的代码。很抱歉给您带来不便@Both

标签: javascript json svg


【解决方案1】:

这是一篇很好的文章,您可以在其中学习如何做到这一点:

http://tympanus.net/codrops/2013/11/05/animated-svg-icons-with-snap-svg/

你可以下载源文件,在“js”目录下你会找到一个使用svg数据的json文件。

您可以考虑使用 Snap.svg,对您有很大帮助:

http://snapsvg.io/

希望对你有帮助!

【讨论】:

【解决方案2】:

这是工作结果..

<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"}
];
for ( var i = 0 ; i < data.length ; i++){
var rect = document.createElementNS(svgNS,'rect');
var width = data [i].duration ;
rect.setAttribute('x',20);
rect.setAttribute('y',10);
rect.setAttribute('width',data[i].duration);
rect.setAttribute('height',50);
rect.setAttribute('fill',data[i].color);
}};
</script>

【讨论】:

    猜你喜欢
    • 2020-12-06
    • 1970-01-01
    • 1970-01-01
    • 2015-07-17
    • 2014-10-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多