![](/img/trans.png)
[英]Is it possible to set the inner HTML of an element with a file using d3js?
[英]Looping through a set of images using D3js
我刚刚开始研究D3js,现在开始关注SVG的工作原理。 我不是设计师,如果可以使用一个简单的原型,我希望让一些设计团队加入d3js。
我想要的是一个图像列表,这些图像是我的数据集,然后在该图像集中的第一个图像中淡出,然后在5秒后将其淡出,然后在下一个图像中淡出。 这将继续遍历该集合。
如果您可以指向我一些链接或提供一些简单的代码来开始我的旅程,那就太好了。
d3的基本功能与HTML以及SVG一样都可以正常工作。 还有一些特定于svg的附加功能,但是所有这些功能的名称都带有svg,例如用于绘制图表轴的d3.svg.axis
。 但是,核心概念适用于所有元素,即您可以创建与数据集匹配的元素。
因此,是的,您可以仅使用HTML <img>
元素创建一个简单的d3示例。 您将要创建一个数据集,该数据集是一个Javascript数组,其中每个要创建的图像在数组中都有一个条目。
举一个简单的例子,假设您的服务器返回了一个由对象数组组成的JSON文件。 每个对象都有两个属性,图像URL和标题文本。 现在,您可以使用d3的文件读取方法来读取和解析JSON文件,或者您可以使用最喜欢的任何一种方法对其进行解析。 无论如何,最终效果应该与您像这样对它进行硬编码时大致相同:
var dataArray = [{url:"image1.jpeg", title:"First image"},
{url:"image2.png", title:"Second image"},
{url:"image3.png", title:"Third image"}];
然后,声明一个要放入<img>
元素的空d3选择,并使用d3的data-join方法创建匹配的元素。 你这样做
selectAll
选择,该选择器将特定于您要创建的元素; enter()
方法访问占位符条目,以获取没有匹配元素的数据值,并创建它们; 样例代码:
var slides = d3.select("div.slideshowContainer") //1. select parent
.selectAll("img") //2. select children (all images in the div, none to start)
.data( dataArray ); //3. bind to the array
slides.enter() //4. access the placeholders
.append( "img" )
//create an <img> as a child of the parent div, one for each placeholder
.attr( "class", "slide" );
//set classes and any other attributes that won't change
slides.attr("src", function(d){ return d.url;})
.attr("title", function(d){ return d.title;});
//set attributes based on the data object bound to each element
//when you give a function as the value of an attr() call,
//d3 will call it with the data object as the first parameter
为了获得简单的幻灯片放映效果,您想使用d3过渡随着时间的推移更改幻灯片的可见性:
slides.attr("opacity", 0) //start invisible
.transition().duration(1000) //schedule a transition to last 1000ms
.delay(function(d,i){return i*2000;})
//Delay the transition of each element according to its index
// in your selection so that it won't start to appear
// until one second after the last image reached full opacity.
//The second parameter passed to any function you give to d3
// is usually the index of that element within the current selection.
.attr("opacity", 1);
//set the end-value of the transition to full opacity
单独地,上面的代码将创建一系列并排显示的图像,您需要调整CSS,以使它们在容器内完全相对放置。
这是对一些非常主要的d3概念的快速了解。 逐步学习教程以获取更多经验。
大多数教程示例都使用SVG,尽管“让我们制作条形图”中的初始示例使用彩色的<div>
元素作为条形,并且还有另外两个示例。 但是,所有示例都可能有用:仅尝试着重于如何创建元素以及如何设置属性,样式和文本内容,而不必担心SVG属性和元素类型如何与图形功能相关联。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.