如何根据元素在javascript中的距离更改图像大小

时间:2022-11-11 12:25:38

I'd like to draw a line that connects two circles, but when the window is being re-sized, the distance between the two circles changes therefore the height of the line image should change accordingly. Here is what I have now but it only does it once when the page loads, but I want the image height to be dynamically changing as the window is being re-sized:

我想绘制一条连接两个圆的线,但是当重新调整窗口大小时,两个圆之间的距离会发生变化,因此线图像的高度应相应改变。这是我现在拥有的,但它只在页面加载时执行一次,但我希望图像高度随着窗口重新调整大小而动态变化:

function getDistance(id1, id2){
    distX = id1.offsetLeft - id2.offsetLeft;
    distY = id1.offsetTop - id2.offsetTop;
    distance = Math.sqrt(distX*distX + distY*distY);
    return distance;
    console.log(distance);
}


var myImage = new Image(50, 100);

myImage.src = 'images/line.png';
myImage.height = getDistance(circle1, circle2);
document.getElementById("line").appendChild(myImage);

2 个解决方案

#1


You have to add an event listener to the window resize event.

您必须向窗口调整大小事件添加事件侦听器。

Add the following snippet on the end of your code:

在代码末尾添加以下代码段:

window.addEventListener('resize', function(){
    myImage.height = getDistance(circle1, circle2);
}, false);

Doing this way instead of assigning an event on window.onresize allows binding multiple functions to the event.

这样做而不是在window.onresize上分配事件允许将多个函数绑定到事件。

You can also use jQuery if you have it loaded on your site:

如果您在网站上加载了jQuery,也可以使用它:

$(window).bind('resize',function(){/*code*/});

#2


Try this:

var myImage = new Image(50, 100);
myImage.id  = 'line-image';
myImage.src = 'images/line.png';
document.getElementById("line").appendChild(myImage);

window.onresize = function() {
   document.getElementById('line-image').height = getDistance(circle1, circle2);
}

#1


You have to add an event listener to the window resize event.

您必须向窗口调整大小事件添加事件侦听器。

Add the following snippet on the end of your code:

在代码末尾添加以下代码段:

window.addEventListener('resize', function(){
    myImage.height = getDistance(circle1, circle2);
}, false);

Doing this way instead of assigning an event on window.onresize allows binding multiple functions to the event.

这样做而不是在window.onresize上分配事件允许将多个函数绑定到事件。

You can also use jQuery if you have it loaded on your site:

如果您在网站上加载了jQuery,也可以使用它:

$(window).bind('resize',function(){/*code*/});

#2


Try this:

var myImage = new Image(50, 100);
myImage.id  = 'line-image';
myImage.src = 'images/line.png';
document.getElementById("line").appendChild(myImage);

window.onresize = function() {
   document.getElementById('line-image').height = getDistance(circle1, circle2);
}