使用变量缩放图像

时间:2017-10-15 16:41:30

标签: javascript html image variables scale

我试图使用变量而不是石刻比例来缩放图像。我知道使用" scale(0.5,0.5)"有效,但我想做" scale(x,y)"因此比例因子根据x和y的变量而变化,但是当我尝试这样做时,图像将不再像它具有设定的比例因子时那样缩放。我怎么解决这个问题?谢谢你的帮助。这是我的意思的一个例子。

<!DOCTYPE html>
<html>
<body>

<img id="myImg" src="img_pulpit.jpg">

<button onclick="myFunction()">Try it</button>

<script>
var a = document.getElementById("myImg");
var d = 5
var e = 10
var f = d/e
var g = 10
var h = 30
var i = g/h

function myFunction() {
document.getElementById("myImg").style.WebkitTransform = "scale(f, i)";
}

</script>
</body>
</html>

3 个答案:

答案 0 :(得分:2)

只需使用字符串连接("scale(" + f + ", " + i + ")")或字符串插值(`scale(${f}, ${i})`)。

答案 1 :(得分:1)

function myFunction() {
    document.getElementById("myImg").style.WebkitTransform = "scale(" + f + "," + i + ")";
}

答案 2 :(得分:1)

你需要使用concat f和i的值

document.getElementById("myImg").style.WebkitTransform = "scale("+f+","+i+")";

&#13;
&#13;
<!DOCTYPE html>
<html>
<body>

<img id="myImg" src="https://lh3.googleusercontent.com/gN6iBKP1b2GTXZZoCxhyXiYIAh8QJ_8xzlhEK6csyDadA4GdkEdIEy9Bc8s5jozt1g=w300">

<button onclick="myFunction()">Try it</button>

<script>
var a = document.getElementById("myImg");
var d = 5
var e = 10
var f = d/e
var g = 10
var h = 30
var i = g/h

function myFunction() {
document.getElementById("myImg").style.WebkitTransform = "scale("+f+","+i+")";
}

</script>
</body>
</html>
&#13;
&#13;
&#13;