SVG图像的自动宽度和高度 [英] Auto width and height for SVG image
问题描述
我是SVG
的新手,如果这是一个菜鸟问题,请原谅.我试图弄清楚如何使图像以参考图像的完整宽度和高度显示.我正在使用D3.js
来构建图形,并且希望徽标出现在角落.问题是图像href
将使用javascript进行设置,因此被引用的图像永远不会是固定的宽度或高度.我想要的是图像以其整个宽度和高度显示,而不是按比例放大或缩小.我希望能够基于图像的内容自动设置图像的宽度和高度,例如将width
和height
属性设置为auto
.但是,这只会导致图像无法显示.
I am new to SVG
, so sorry if this is a bit of a noob question. I am trying to figure out how to get an image to display with the full width and height of the referenced image. I am using D3.js
to build a graph and I want a logo to appear in the corner. The problem is that the image href
will be set using javascript, so the image being referenced is never a fixed width or height. What I am wanting is the image to display in it's full width and height, not scaled up or down. What I was hoping for is the ability to automatically set the width and height of the image based on it's content, such as setting the width
and height
attributes to auto
. This however just results in the image not being shown.
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');
我该如何指定必须根据引用的图像大小动态确定SVG图像width
和height
?
How would I go about specifying that the SVG image width
and height
must be dynamically determined based on the referenced image size?
推荐答案
我不认为'auto'是svg图像元素的'length'attr的有效值.在此处中查看规范.您可能要使用"100%"
I don't think 'auto' is a valid value for the 'length' attr of a svg image element. Take a look at the spec here. You might want to use '100%'
您可以加载图像,然后检查加载的宽度和高度.
You could load the image then inspect the width and height onload.
JSFiddle: http://jsfiddle.net/WQBPC/4/
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)
}
这篇关于SVG图像的自动宽度和高度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!