david0116
david0116

Reputation: 103

SVG image scale from center with slider

I made a Jquery ui slider to dynamically control the size of SVG image in the mask. The image gets resized from left-top corner. I'm wondering to know that is that possible to resize the image from center? Any idea would be appreciated.

https://jsfiddle.net/david7418/o497akje/

  obj = Snap(".cat");
  obj.drag();
  var dimens = obj.node.getBoundingClientRect();
  $("#slider").slider({
      max: dimens.width,
      min: dimens.width / 5,
      step: 1,
      value: dimens.width,
      slide: function(event, ui) {
          obj.attr({
              width: ui.value
          });
      }
  });

Upvotes: 0

Views: 698

Answers (2)

Paul LeBeau
Paul LeBeau

Reputation: 101820

You also need to move the image's x and y and height as you adjust the width.

I also changed the slider to return a percentage. I think it's a little more obvious what's going on that way.

$(function() {
   obj = Snap(".cat");
   var dimens = obj.node.getBoundingClientRect();     
   console.log(dimens.width)
   $( "#slider" ).slider({
      max: 100, 
      min: 100/5, 
      step:1, 
      value:dimens.width,
      slide: function( event, ui ) {
         w = ui.value * dimens.width / 100;
         h = ui.value * dimens.height / 100;
         obj.attr({
            width: w,
            height: h,
            x: (dimens.width - w)/2,
            y: (dimens.height - h)/2
         });
      }
   });
});

Updated fiddle

Upvotes: 2

Marco Hengstenberg
Marco Hengstenberg

Reputation: 864

With SVG the default position for transforms to start is the top left corner. So, in order to override this, you need to explicitly set a transform-origin on the SVG like this:

svg {
    transform-origin: center center;
}

Upvotes: -1

Related Questions