简体   繁体   English

尝试用javascript制作一个功能来放大图像

[英]Trying to make a function with javascript to enlarge an image

I've got this function: 我有这个功能:

function zoomImage(i, image, currentWidth, currentHeight, targetWidth, targetHeight){
    var widthStep = (targetWidth - currentWidth) / 100;
    var heightStep = (targetHeight - currentHeight) / 100;
    var newWidth = Math.ceil( currentWidth + i * widthStep );
    var newHeight = Math.ceil( currentHeight + i * heightStep );
    i++;
    var imageZ = document.getElementById(image);
    imageZ.style.width = newWidth+"px";
    imageZ.style.height = newHeight+"px";
    while( i <= 100 )
        t = setTimeout("zoomImage(i, image, currentWidth, currentHeight, targetWidth, targetHeight)",10);
}

Called like this: 这样称呼:

zoomImage(0, "image1", 200, 150, 260, 195);

But for some reason the page won't stop loading and crashes eventually. 但由于某种原因,页面最终不会停止加载和崩溃。 Also the image doesn't get bigger. 图像也不会变大。 What am I doing wrong here? 我在这做错了什么?

I assume you initialized i outside the function. 我假设你在函数之外初始化了i That's the i that will always get passed in when you make your recursive call. 当你进行递归调用时,那就是i永远传入的那个。 This is because when you give a string to setTimeout , it is evaluated in the global scope. 这是因为当您将字符串提供给setTimeout ,将在全局范围内对其进行求值。

This means that the i++ inside the function only affects the local i , and not the global i , so i is never incremented not incremented beyond 1 + the global value. 这意味着函数内部的i++仅影响局部i ,而不影响全局i ,因此i 不会递增,不会递增1 +全局值。

Instead pass an anonymous function that invokes the recursive call. 而是传递一个匿名函数来调用递归调用。 This way you're actually passing the incremented i . 这样,您实际上就是传递了递增的i

while( i <= 100 )
    setTimeout(function() {
         zoomImage(i, image, currentWidth, currentHeight, targetWidth, targetHeight);
    },10);

Of course, as noted in the comments, while doesn't seem like the right choice here. 当然,正如评论中所指出的那样, while这似乎不是正确的选择。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM