【发布时间】:2014-02-07 05:29:48
【问题描述】:
需要提前道歉:为了篇幅和我的无知。我正在尝试自学新概念:d3.js 和精灵表。精灵表的概念很容易理解,但我很困惑如何将它集成到 d3 中。基本上我想要做的是从精灵表中选择我想用作图像的精灵,然后使用 d3 在页面的其他位置显示这个选定的精灵,并且很可能是同一个精灵的多个副本。
供参考的实际精灵表(请参阅下面的免责声明):
以下是问题:
1)我将精灵表添加到我的html中,现在硬编码<clipPath>,这将显示我想要的特定精灵,但是,精灵的尺寸/位置就像显示整个精灵表一样。我怎样才能只“捕获”精灵本身,而不仅仅是隐藏未使用的精灵?在下图中,我想在 d3 mouseover 事件(第 2 部分)中使用单个“图标”。
修改这个例子:SO: Display CSS image sprite in SVG without using foreignObject
HTML
<svg id="mySvg1" width="100%" height="100%">
<defs>
<clipPath id="c">
<rect x="135" y="0" width="150" height="150"/>
</clipPath>
</defs>
<image transform="scale(1.0)" x="0" y="0" width="550" height="420" xlink:href="static/img/iconSheet.png" clip-path="url(#c)"/>
<svg>
结果
2) 我可以使用<pattern> 来确定要在 d3 对象/事件中显示的图像。就像在矩形中显示图形一样。但这似乎不适用于大图像(精灵表)?如果我尝试使用精灵表本身及其在模式中的原生尺寸,它会变得奇怪和模糊。如果我们解决了第 1 部分,我们可能会忽略第 2 部分,但这对于一般知识/未来使用来说会很好理解。
修改这个例子:SO: Adding an image within a circle object in d3 javascript?
HTML
<svg id="mySvg" width="550" height="420">
<defs id="mdef">
<pattern id="image" x="0" y="0" height="550" width="420">
<image transform="scale(1.0)" x="0" y="0" width="550" height="420" xlink:href="static/img/iconSheet.png"></image>
</pattern>
</defs>
</svg>
Javascript:
var svgContainer = d3.select("div#content-main").append("svg")
.attr("width", 740)
.attr("height", 760)
.attr("class", "mySvg")
.style("border", "none");
svgContainer.append("rect")
.attr("class", "logo")
.attr("x", 0)
.attr("y", 0)
.attr("width", 550)
.attr("height", 420)
.style("fill", "transparent")
.style("stroke", "black")
.style("stroke-width", 0.25)
.on("mouseover", function(){
d3.select(this)
.style("fill", "url(#image)");
})
.on("mouseout", function(){
d3.select(this)
.style("fill", "transparent");
});
结果
3) 如果有更有效的方法来实现这一点,我愿意接受建议。我只是坚持使用 d3 模型,因为我已经渲染了一个 svg 对象,我只需要向它添加一些东西。
免责声明:这些图标不是我的作品!我仅将这些图标用于教育目的。作者的链接在这里:Fitness Icons
【问题讨论】:
-
This question 可能会有所帮助。
标签: javascript svg d3.js sprite-sheet