anseki / plain-draggable

The simple and high performance library to allow HTML/SVG element to be dragged.
https://anseki.github.io/plain-draggable/
MIT License
774 stars 99 forks source link

How to set initial position? #134

Closed g40 closed 1 year ago

g40 commented 1 year ago

One or more child image elements are added dynamically in code. How best to ensure that the new element is properly snapped into position?

Edited for posterity. Was missing let rect = parent.getBoundingClientRect();

// add an child image to the parent with image src at cx and cy. 
function addChildImage(parent,src,cx,cy)
{
    const dx = 15;
    const dy = 100;
    let rect = parent.getBoundingClientRect();
    let ix = Math.max(0,cx - (cx % dx) + rect.left);
    let iy = Math.max(0, cy - (cy % dy) + rect.top);
    let img = new Image();  
    img.id = "draggable_" + global_id;
    img.src = src;
    img.style = "position:absolute;left:" + ix + "px;top:" + iy + "px;";
    parent.appendChild(img);
    let draggable = new PlainDraggable(img, 
    { 
        snap: { x: { step: dx }, y: { step: dy }, gravity: dy, top: true },
        autoScroll: true
    });
    //
    global_id+=1;
}
anseki commented 1 year ago

:smile: