gpt4 book ai didi

javascript - 获取响应式嵌入图像的高度

转载 作者:行者123 更新时间:2023-11-28 15:19:11 25 4
gpt4 key购买 nike

我用 d3js 库生成了 SVG。 SVG 内部是附加图像。我想要做的是获取图像高度,而不是原始高度,而是调整大小以适合容器(100% 宽度)时图像的高度。

这是我的麻烦的一个例子:

var svg = d3.select(".preview").append("svg")
.attr({
width: "100%"
})


var exampleImage = svg.append("image")
.attr("xlink:href", "https://farm8.staticflickr.com/7187/6895047173_d4b1a0d798.jpg")
.attr({
class: "example-image",
width: "100%",
height: "100%"
});


var imgWidth = $(".example-image").width();
var imgHeight = $(".example-image").height();

$("h4").html(imgWidth + " x " + imgHeight);

$(document).ready(function() {

$("h3").html(imgWidth + " x " + imgHeight);

var imgObj = new Image();

imgObj.src = "https://farm8.staticflickr.com/7187/6895047173_d4b1a0d798.jpg";
imgObj.onload = function() {
$("h1").html("original size: " + imgObj.width + " x " + imgObj.height);
}
});
$("h2").html("Need height of resized image appended to svg, NOT original");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>

<div class="preview" style="width: 200px; height: auto;"></div>

<h4></h4>
<h3></h3>
<h2></h2>
<h1></h1>

请注意,图像的高度将用于设置整个 svg 元素的高度。

这是 jsbin 中的相同片段:jsbin

最佳答案

有几种方法可以做你想做的事。其中之一是使用 getBBox() :

var imgWidth = d3.select(".example-image").node().getBBox().width;
var imgHeight = d3.select(".example-image").node().getBBox().height;

这里是你的代码有那个变化:

var svg = d3.select(".preview").append("svg")
.attr({
width: "100%"
})


var exampleImage = svg.append("image")
.attr("xlink:href", "https://farm8.staticflickr.com/7187/6895047173_d4b1a0d798.jpg")
.attr({
class: "example-image",
width: "100%",
height: "100%"
});


var imgWidth = d3.select(".example-image").node().getBBox().width;
var imgHeight = d3.select(".example-image").node().getBBox().height;

$("h4").html(imgWidth + " x " + imgHeight);

$(document).ready(function() {

$("h3").html(imgWidth + " x " + imgHeight);

var imgObj = new Image();

imgObj.src = "https://farm8.staticflickr.com/7187/6895047173_d4b1a0d798.jpg";
imgObj.onload = function() {
$("h1").html("original size: " + imgObj.width + " x " + imgObj.height);
}
});
$("h2").html("Need height of resized image appended to svg, NOT original");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>

<div class="preview" style="width: 200px; height: auto;"></div>

<h4></h4>
<h3></h3>
<h2></h2>
<h1></h1>

PS:这是建设性的批评:不要不要混合使用 jQuery 和 D3。这不仅是不必要的,而且会让事情悄无声息地崩溃。

关于javascript - 获取响应式嵌入图像的高度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46535089/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com