我是新手SVG,很抱歉,如果这是一个noob问题.我试图弄清楚如何使用引用图像的全宽和高度来显示图像.我正在使用D3.js构建图表,我希望在角落里出现一个徽标.问题是图像href将使用javascript设置,因此被引用的图像永远不是固定的宽度或高度.我想要的是要在其全宽和高度上显示的图像,而不是按比例放大或缩小.我所希望的是能够根据图像的内容自动设置图像的宽度和高度,例如将图像width和height属性设置为auto.然而,这只会导致图像无法显示.
d3.select("body")
.append("svg")
.attr('id','mySVG')
.attr({
"width": "100%",
"height": "100%"
})
.attr("viewBox", "0 0 " + width + " " + height )
.attr("preserveAspectRatio", "none");
d3.select('#mySVG')
.append('image')
.attr('image-rendering','optimizeQuality')
.attr('height','auto') <--- This does not work
.attr('width','auto') <--- This does not work
.attr('xlink:href', logoUrl)
.attr('x','0')
.attr('y','0');
Run Code Online (Sandbox Code Playgroud)
我如何指定SVG图像width并且height必须根据参考图像大小动态确定?
Wol*_*des 23
我不认为'auto'是svg图像元素的'length'attr的有效值.看看这里的规格.您可能想要使用'100%'
您可以加载图像,然后检查宽度和高度onload.
JSFiddle:http://jsfiddle.net/WQBPC/4/
var logoUrl = 'http://placehold.it/100x50&text=Logo';
//SVG Setup stuff
var svg = d3.select("body").append("svg")
.attr('id','mySVG')
.attr({
"width": '100%',
"height": '100%'
})
var svg_img= svg.append('image')
.attr('image-rendering','optimizeQuality')
.attr('x','0')
.attr('y','0');
//Load image and get size.
var img = new Image();
img.src = logoUrl;
img.onload = function() {
var width = this.width;
var height = this.height;
svg_img .attr('height', height)
.attr('width',width)
.attr('xlink:href', logoUrl)
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
37185 次 |
| 最近记录: |