Reputation: 101
I recently posted a question regarding how to scale an image using the input type="range" element. I recieved an excellent answer from user Prisoner:
<input id="ranger" type="range" min="1" max="100" value="100" />
<hr />
<img id="image" src="http://google.com/images/logo.png" width="275" height="95" />
var ranger = document.getElementById('ranger'),
image = document.getElementById('image'),
width = image.width,
height = image.height;
ranger.onchange = function(){
image.width = width * (ranger.value / 100);
image.height = height * (ranger.value / 100);
}
HOWEVER! This scales the image towards its upper left corner and I need an image that scales towards its center. How do I achieve this? Can't seem to get it to work using text-align:center or anything...
Thanks in advance!
Upvotes: 0
Views: 295
Reputation: 6937
Yes. Assuming your images start out at full width, you just need to take into account the image center, then reposition the image on size change.
add to css:
img{ position: relative; }
and amend your function like so:
ranger.onchange = function(){
image.width = width * (ranger.value / 100);
image.height = height * (ranger.value / 100);
image.style.left=(width/2-image.width/2+"px");
image.style.top=(height/2-image.height/2+"px");
}
Here's a working jsFiddle
By the way, did you intend to allow scaling the image down until ~ 1pX1px size? What's the point of that?
Upvotes: 1
Reputation: 707
Use align option of img tag.
<img id="image" src="http://google.com/images/logo.png" align="middle" width="275" height="95" />
Upvotes: 0