如何动态设置图像大小?

时间:2014-01-29 22:27:14

标签: javascript html css

我正在尝试将图像元素放在背景图像的顶部。

图像元素需要根据用户的动作制作动画。我有我的背景图像css如下:

CSS

body {
    background: url('test.png') no-repeat center center;
    -webkit-background-size: 100% auto;
    background-color: #00ABBA;
    -moz-background-size: 100% auto;
    -o-background-size: 100% auto;
    background-size: 100% auto;
}

HTML

<div> <img src='ball.png' /> <div&GT;

因此背景图像将始终为屏幕的100%并具有响应性。

但是,图像元素有一个设置大小,我不知道如何设置大小以适应背景图像大小(较大的屏幕有较大的背景图像/较小的屏幕有较小的背景图像)。

任何人都可以帮我设置尺寸与背景图像一致的图像元素吗?非常感谢!

1 个答案:

答案 0 :(得分:0)

你有几个选择。

大部分归结为将背景图像的某些“基本尺寸”与其实际尺寸进行比较。

假设你的背景宽1000像素,高700像素,你可以选择你的数字。这是我们的基本规模。

var baseWidth = 1000;
var baseHeight = 700;

现在我们需要知道我们最终得到了什么。为此,我们获得具有背景的元素的大小。假设为了简单起见,div表示ID为“背景”。

var backgroundElement = document.getElementById('background');
var currentWidth = backgroundElement.width;
var currentHeight = backgroundElement.height;

(注意,填充,边距,边框等可能会影响宽度的大小,所以你可能想要使用像jQuery这样的第三方库,或者如果它们适用于确保你自己考虑那些适当的测量)。

然后,相对而言,我们想知道我们改变了多少。

var scaleWidth = currentWidth / baseWidth;
var scaleHeight = currentHeight / baseHeight;

如果我们大于基数,则scale *大于0.如果它更小,则scale *小于零。

现在,我们决定我们想做什么。我们假设图像元素的id为“image”。

var image = document.getElementById('image');

如果我们想要增加图像而不关心保存纵横比:

image.width = image.width * scaleWidth;
image.height = image.height * scaleHeight;

如果我们确实想保存宽高比并希望将其全部保留在div中。

image.width = image.width * Math.min(scaleWidth, scaleHeight);
image.height = image.height * Math.min(scaleWidth, scaleHeight);

(注意,如果宽高比可能会发生剧烈变化,那么该片段会更复杂一些,因为您必须确保结果尺寸足够小,以便在事后适合。有时您需要的尺度会更小比scaleWidth和scaleHeight都要好。

如果您想要移动它的位置,请将其置于绝对位置,然后按比例移动它。

// Assumes it already has an absolute position of top and left already set.
image.style.left = parseInt(image.style.left.replace(/[a-z]+$/, '') * scaleWidth;
image.style.top = parseInt(image.style.top.replace(/[a-z]+$/, '')) * scaleHeight;

等等......

基本上,一旦你确定了基本尺寸并知道你的尺度,你就可以开始相对于你的基础进行调整,然后可以根据你的背景进行调整。