javascript – How to convert css pixels to css3 scale (x,y)-ThrowExceptions

Exception or error:

I have a div whose initial width and height are set by the user. When a user zooms in the browser(ctrl+ or ctrl-) the initial width and height of that div changes, say a user zooms in 175%, the aspect ratio of that div stays the same because the width and height is adjusted. Is there a way to replicate this by dynamically setting transform: scale(x,y). I have tried several thing but can’t seem to find a solid solution.

How to solve:

Solution seems pretty strain-forward. Store scale somewhere, then increase/decrease it on button’s click:

(function () {
  function zoom(element, scale) {
    element.style.webkitTransform =
      element.style.transform = 'scale(' + scale + ')';
    return scale;
  }

  var zoomable = document.querySelector('.zoomable');
  var scale = 1;

  document.querySelector('#zoomin')
    .addEventListener('click', function () {
      scale = zoom(zoomable, scale * 2);
    });

  document.querySelector('#zoomout')
    .addEventListener('click', function () {
      scale = zoom(zoomable, scale * 0.5);
    });
})();

Demo: http://jsbin.com/aJagofU/1/edit?js,output

Leave a Reply

Your email address will not be published. Required fields are marked *