简体   繁体   中英

How to get the position of a draggable element in a smaller div and translate that to a large div

What i'm basically creating is an electron program that loops a video containing adverts. The video spans the entire window.

I have a second, smaller window used to configure things about the video window in real time and one of those things is being able to add a message overlayed on the video. Here's an image to show you what I mean: https://i.imgur.com/9SneVOT.png

The blue rectangle on the smaller video in the foreground can be dragged around and represents a message that will be displayed over the video. If I save the coordinates of that rectangle and create an element on the main video in the background the coordinates don't match up due to the different sizes of the windows, so how do I take those coordinates and make them work for the bigger window?

Each pixel in the smaller div equals X pixels in the bigger div. That's the ratio to multiply with. Let's assume mouse movement inside smaller div is like dragging and affecting the bigger div.

 var small = document.querySelector(".small"); var big = document.querySelector(".big"); var rectangle = document.querySelector(".rectangle"); var ratioX = big.clientWidth / small.clientWidth var ratioY = big.clientHeight / small.clientHeight small.addEventListener("mousemove", function(ev) { var mx = ev.offsetX var my = ev.offsetY rectangle.style.left = mx * ratioX + "px" rectangle.style.top = my * ratioY + "px" })
 .small { width: 100px; height: 50px; border: 1px solid black; }.big { width: 300px; height: 150px; border: 1px solid black; position: relative; overflow: hidden; }.rectangle { width: 20px; height: 20px; background: blue; position: absolute; }
 Mouse over this: <div class="small"> </div> Will move this: <div class="big"> <div class="rectangle"> </div> </div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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