jQuery Drag/Resize with CSS Transform Scale

前端 未结 13 1992
忘了有多久
忘了有多久 2020-11-27 13:39

I am applying a CSS transform (and the browser specific -webkit, -o etc):

transform: matrix(0.5 , 0 , 0, 0.5, 0 , 0);

to a div then using jQuery\'s draggable

13条回答
  •  Happy的楠姐
    2020-11-27 14:23

    Here is my solution. Some of the code posted above did not work for me.

    I have a dragable image and I apply CSS transform rotate and scale onto that image. Once I scale/rotate it the position is off at drag-start. To fix it I calculate the setpoint difference from stop to start and on-drag apply a new setpoint with the difference factored in.

    var $img = $("#my-image-id");
    
    $img.posLeft  = 0;
    $img.posTop  = 0;
    $img.diffLeft  = 0;
    $img.diffTop  = 0;
    
    $img.draggable({
      start: function( event, ui ) {
        //check the difference from start to stop setpoints
        $img.diffLeft  = $img.posLeft-ui.position.left;
        $img.diffTop  = $img.posTop-ui.position.top;
        //console.log('start x: '+Math.floor(ui.position.left)+' y: '+Math.floor(ui.position.top));
        //console.log('diff x: '+Math.floor($img.posLeft-ui.position.left)+' y: '+Math.floor($img.posTop-ui.position.top));
      },
      drag: function( event, ui ) {
        //fix the offset bug that is applied after CSS transform, to do that just add the value difference
        ui.position.left = ui.position.left+$img.diffLeft;
        ui.position.top = ui.position.top+$img.diffTop;
        //console.log('drag x: '+ui.position.left+' y: '+ui.position.top);
      },
      stop: function( event, ui ) {
        //save the last applied setpoints
        $img.posLeft = ui.position.left;
        $img.posTop = ui.position.top;
        //console.log('stop x: '+Math.floor(ui.position.left)+' y: '+Math.floor(ui.position.top));
      }
    });
    

    The CSS transform-origin trick does fixes the bug for scale only. Rotation should be around center so you want to keep the default 50% 50%.

提交回复
热议问题