0

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);
UrsinusTheStrong
  • 1,239
  • 1
  • 16
  • 33
bunnyHat
  • 17
  • 7

2 Answers2

0

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);
}
Rob M.
  • 35,491
  • 6
  • 51
  • 50
0

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.

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

$(window).bind('resize',function(){/*code*/});
Pedro Sanção
  • 1,328
  • 1
  • 11
  • 16