div scale to preserve aspect ratio - javascript

I have a layout like so:
HTML
<div id="container">
<div id="zoomBox">
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
</div>
</div>
CSS
#container { width:100%; }
#box { height:1000px;width:920px; }
What I am trying to do is scale my container and the contents to preserve the aspect ratio it is currently in. Right now I use the transform: scale() and it works great but I am having serious issues with it working in Internet Explorer.
This is my code so far. Does anyone have any other suggestions in making this work nicely in IE?
function zoomProject(percent)
{
$maxWidth = $("#container").width();
if(percent == 0)
percent = $maxWidth/920;
$("#zoomBox").css({
'transform': 'scale(' + percent + ')',
'-moz-transform': 'scale(' + percent + ')',
'-webkit-transform': 'scale(' + percent + ')',
'-ms-transform': 'scale(' + percent + ')'
});
}

I don't have jquery set up but an example using raw html and javascript. It probaly wont run on IE as is (older ie doesn't use some of the same syntax but has the same functionality) but once you switch it over to jquery it should be fine.
Code:
function zoomProject(ratio) {
var i, height;
var boxes = document.getElementsByClassName("box");
for (i=0;i<boxes.length;i++) {
height = (boxes[i].offsetWidth * ratio) + "px";
boxes[i].style.height = height;
}
}
zoomProject(.1);
.container { background: red; width: 100%; height: 100%; }
.box { background: blue; width: 100%; border: 1px solid white;}

Try without transform:
new_width = width * percent / 100;
new_height = height * percent / 100;
$("#zoomBox").css('width',new_width);
$("#zoomBox").css('height',new_height);

Related

Transform orgin not being implemented

Attempting to transform an images scale (zoom) BUT maintain it inside it's parents left and top div so only trying to transform it down and to the right. Setting the transform orgin does not seem to work, what am I missing?
the following code zooms the image on each button click, but pushes the left and top out of the parent div.
$('element').click(function{
$('#element').css({'transform':'scale(' + scale + ')' });
$('#element').css({'transform-orgin':'top left'});
})
<div style "max-wdith:1080px; height: 700px; overflow-x:scroll; overflow-y:scroll">
<img id="element" src=" src="https://images.techhive.com/images/article/2017/03/castle_moat-100714623-large.jpg" " class="img-flud">
</div>
You can try the below code
var x = 400 + 'px';
var y = 300 + 'px';
$('#element').css({
'transform-origin': x + ' ' + y + ' 0px',
'-webkit-transform-origin': x + ' ' + y + ' 0px'
});
Updated answer!
const btn = document.querySelector('button');
function zoomIn(e) {
const scale = 0.1;
const img = document.querySelector('#my-image');
$('#my-image').css({transformOrigin: "top left", transform: 'scale(' + scale + ')'});
}
btn.addEventListener('click', zoomIn);
div {
width: 400px;
height: 400px;
border: 1px solid black;
overflow: hidden;
float: left;
}
div > img {
width: 100%;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<img id="my-image" src="https://images.techhive.com/images/article/2017/03/castle_moat-100714623-large.jpg" />
</div>
<button>Zoom In</button>

Need help scaling and rotating an image in a viewport

I have the code in this JSFidle - https://jsfiddle.net/pmi2018/smewua0k/211/
Javascript
$('#rotate').click(function(e) {
updateImage(90, 0)
console.log("rotation");
});
$('#zoom-in').click(function() {
updateImage(0, 0.1);
console.log("Zoomed in");
});
$('#zoom-out').click(function() {
updateImage(0, -0.1);
console.log("Zoomed out");
});
var zoomLevel = 1;
var rotation = 0;
var updateImage = function(angle, zoom) {
zoomLevel += zoom;
var img_scale = ' scale(' + zoomLevel + ') ';
rotation += angle;
if (rotation == 360) {
rotation = 0;
}
var str_rotation = ' rotate(' + rotation + 'deg) ';
console.log("rotation=" + str_rotation + " scale=" + img_scale);
var img = document.getElementById('sam');
img.style.transform = img_scale + str_rotation
//if (angle == 0) {
// img.style.transformOrigin = '0 0';
// img.style.transform = img_scale;
// }
// else {
// img.style.transformOrigin = 'center center';
// img.style.transform = str_rotation;
// }
}
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button type="button" id="zoom-in">zoom in</button> <button type="button" id="zoom-out">zoom out</button>
<div id=imageblock>
<img id="sam" src="http://placekitten.com/g/250/250" />
</div>
<div>
<a id="rotate" href="#">Rotate 90 degrees</a>
</div>
CSS
#imageblock {
width: 300px;
height: 300px;
border: 1px solid #000000;
overflow: auto;
display: block;
}
#sam {
transform-origin: center, center;
}
The problem is I need the have the origin be upper left corner when I scale the image to keep the scaled image in the box; but the origin has to be center, center when I rotate the image to keep the image in the box. However the CSS articles I have read say when rotating and scaling an image, they have to be done together.
I tried applying the rotation and scale separately so I could set the origin correctly (the commented out code), but only the first transform fires, and not the second.
How can I rotate and scale the image in the #imagebox?
Thanks!
Mark
The reason why it "goes together" is because the transform property can only have one origin. So if you apply multiple transformations on a single object, they will all use the same origin.
An easy solution would be to put the image in a div. Then, use the zoom on the div, and the rotate on the image for exemple so that both can have different origins.
$('#rotate').click(function(e) {
updateImage(90, 0)
});
$('#zoom-in').click(function() {
updateImage(0, 0.1);
});
$('#zoom-out').click(function() {
updateImage(0, -0.1);
});
var zoomLevel = 1;
var rotation = 0;
var updateImage = function(angle, zoom) {
zoomLevel += zoom;
var img_scale = ' scale(' + zoomLevel + ') ';
rotation += angle;
if (rotation == 360) {
rotation = 0;
}
var str_rotation = ' rotate(' + rotation + 'deg) ';
// Here I modified the syntax just a bit, to use JQuery methods instead of pur Javascript. I hope you are ok with it
// I modify the image rotate property, and then the div scale property
$('#sam').css('transform',str_rotation)
$('#zoom').css('transform', img_scale);
}
#imageblock {
width: 300px;
height: 300px;
border: 1px solid #000000;
overflow: auto;
display: block;
overflow: hidden; /* To hide the scrollbar when you zoom in */
}
#zoom {
transform:scale(1);
transform-origin:top left;
}
#sam {
transform: rotate(0deg)
transform-origin: center center;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button type="button" id="zoom-in">zoom in</button> <button type="button" id="zoom-out">zoom out</button>
<div id=imageblock>
<div id="zoom"> <!-- I added this div -->
<img id="sam" src="http://placekitten.com/g/250/250" />
</div>
</div>
<div>
<a id="rotate" href="#">Rotate 90 degrees</a>
</div>
Also, please note that there is no coma in transform-origin: center center;.
Ask them if you have any questions. I hope it helped !

Using CSS transform scale() to zoom into an element without cropping, maintaining scrolling

Live example: https://jsfiddle.net/b8vLg0ny/
It's possible to use the CSS scale and translate functions to zoom into element.
Take this example, of 4 boxes in a 2x2 grid.
HTML:
<div id="container">
<div id="zoom-container">
<div class="box red">A</div>
<div class="box blue">B</div>
<div class="box green">C</div>
<div class="box black">D</div>
</div>
</div>
CSS:
* { margin: 0; }
body, html { height: 100%; }
#container {
height: 100%;
width: 50%;
margin: 0 auto;
}
#zoom-container {
height: 100%;
width: 100%;
transition: all 0.2s ease-in-out;
}
.box {
float: left;
width: 50%;
height: 50%;
color: white;
text-align: center;
display: block;
}
.red { background: red; }
.blue { background: blue; }
.green { background: green; }
.black { background: black; }
JavaScript:
window.zoomedIn = false;
$(".box").click(function(event) {
var el = this;
var zoomContainer = $("#zoom-container");
if (window.zoomedIn) {
console.log("resetting zoom");
zoomContainer.css("transform", "");
$("#container").css("overflow", "auto");
window.zoomedIn = false;
} else {
console.log("applying zoom");
var top = el.offsetTop;
var left = el.offsetLeft - 0.25*zoomContainer[0].clientWidth;
var translateY = 0.5*zoomContainer[0].clientHeight - top;
var translateX = 0.5*zoomContainer[0].clientWidth - left;
$("#container").css("overflow", "scroll");
zoomContainer.css("transform", "translate(" + 2 * translateX + "px, " + 2 * translateY + "px) scale(2)");
window.zoomedIn = true;
}
});
By controlling the value of translateX and translateY, you can change how the zooming works.
The initial rendered view looks something like this:
Clicking on the A box will zoom you in appropriately:
(Note that clicking D at the end is just showing the reset by zooming back out.)
The problem is: zooming to box D will scale the zoom container such that scrolling to the top and left doesn't work, because the contents overflow. The same happens when zooming to boxes B (the left half is cropped) and C (the top half is cropped). Only with A does the content not overflow outside the container.
In similar situations related to scaling (see CSS3 Transform Scale and Container with Overflow), one possible solution is to specify transform-origin: top left (or 0 0). Because of the way the scaling works relative to the top left, the scrolling functionality stays. That doesn't seem to work here though, because it means you're no longer repositioning the contents to be focused on the clicked box (A, B, C or D).
Another possible solution is to add a margin-left and a margin-top to the zoom container, which adds enough space to make up for the overflowed contents. But again: the translate values no longer line up.
So: is there a way to both zoom in on a given element, and overflow with a scroll so that contents aren't cropped?
Update: There's a rough almost-solution by animating scrollTop and scrollLeft, similar to https://stackoverflow.com/a/31406704/528044 (see the jsfiddle example), but it's not quite a proper solution because it first zooms to the top left, not the intended target. I'm beginning to suspect this isn't actually possible, because it's probably equivalent to asking for scrollLeft to be negative.
Why not just to reposition the TransformOrigin to 0 0 and to use proper scrollTop/scrollLeft after the animation?
https://jsfiddle.net/b8vLg0ny/7/
Updated: https://jsfiddle.net/b8vLg0ny/13/
If you do not need the animation, the TransformOrigin can always stays 0 0 and only the scrolling is used to show the box.
To make the animation less jumpy use transition only for transform porperty, otherwise the transform-origin gets animated also. I have edited the example with 4x4 elements, but I think it makes sense to zoom a box completely into view, thats why I changed the zoom level. But if you stay by zoom level 2 and the grid size 15x15 for instance, then with this approach really precise origin should be calculated for transform, and then also the correct scrolling.
Anyway I don't know, if you find this approach useful.
Stack snippet
var zoomedIn = false;
var zoomContainer = $("#zoom-container");
$(".box").click(function(event) {
var el = this;
if (zoomedIn) {
zoomContainer.css({
transform: "scale(1)",
transformOrigin: "0 0"
});
zoomContainer.parent().scrollTop(0).scrollLeft(0);
zoomedIn = false;
return;
}
zoomedIn = true;
var $el = $(el);
animate($el);
zoomContainer.on('transitionend', function(){
zoomContainer.off('transitionend');
reposition($el);
})
});
var COLS = 4, ROWS = 4,
COLS_STEP = 100 / (COLS - 1), ROWS_STEP = 100 / (ROWS - 1),
ZOOM = 4;
function animate($box) {
var cell = getCell($box);
var col = cell.col * COLS_STEP + '%',
row = cell.row * ROWS_STEP + '%';
zoomContainer.parent().css('overflow', 'hidden');
zoomContainer.css({
transition: 'transform 0.2s ease-in-out',
transform: "scale(" + ZOOM + ")",
transformOrigin: col + " " + row
});
}
function reposition($box) {
zoomContainer.css({
transition: 'none',
transform: "scale(" + ZOOM + ")",
transformOrigin: '0 0'
});
zoomContainer.parent().css('overflow', 'auto');
$box.get(0).scrollIntoView();
}
function getCell ($box) {
var idx = $box.index();
var col = idx % COLS,
row = (idx / ROWS) | 0;
return { col: col, row: row };
}
* { margin: 0; }
body, html { height: 100%; }
#container {
height: 100%;
width: 50%;
margin: 0 auto;
overflow: hidden;
}
#zoom-container {
height: 100%;
width: 100%;
will-change: transform;
}
.box {
float: left;
width: 25%;
height: 25%;
color: white;
text-align: center;
}
.red { background: red; }
.blue { background: blue; }
.green { background: green; }
.black { background: black; }
.l { opacity: .3 }
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
<div id="container">
<div id="zoom-container">
<div class="box red">A</div>
<div class="box blue">B</div>
<div class="box green">C</div>
<div class="box black">D</div>
<div class="box red l">E</div>
<div class="box blue l">F</div>
<div class="box green l">G</div>
<div class="box black l">H</div>
<div class="box red">I</div>
<div class="box blue">J</div>
<div class="box green">K</div>
<div class="box black">L</div>
<div class="box red l">M</div>
<div class="box blue l">N</div>
<div class="box green l">O</div>
<div class="box black l">P</div>
</div>
</div>
I'm answering my own question, since I'm fairly confident that it's actually not possible with the given requirements. At least not without some hackery that would cause problems visually, e.g., jumpy scrolling by animating scrollTop after switching transform-origin to 0, 0 (which removes the cropping by bringing everything back into the container).
I'd love for someone to prove me wrong, but it seems equivalent to asking for scrollLeft = -10, something that MDN will tell you is not possible. ("If set to a value less than 0 [...], scrollLeft is set to 0.")
If, however, it's acceptable to change the UI from scrolling, to zooming and dragging/panning, then it's achievable: https://jsfiddle.net/jegn4x0f/5/
Here's the solution with the same context as my original problem:
HTML:
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
<button id="zoom-out">Zoom out</button>
<div id="container">
<div id="inner-container">
<div id="zoom-container">
<div class="box red">A</div>
<div class="box blue">B</div>
<div class="box green">C</div>
<div class="box black">D</div>
</div>
</div>
</div>
JavaScript:
//
// credit for the approach goes to
//
// https://stackoverflow.com/questions/35252249/move-drag-pan-and-zoom-object-image-or-div-in-pure-js#comment58224460_35253567
//
// and the corresponding example:
//
// https://jsfiddle.net/j8kLz6wm/1/
//
// in a real-world setting, you
// wouldn't keep this information
// on window. this is just for
// the demonstration.
window.zoomedIn = false;
// stores the initial translate values after clicking on a box
window.translateY = null;
window.translateX = null;
// stores the incremental translate values based on
// applying the initial translate values + delta
window.lastTranslateY = null;
window.lastTranslateX = null;
// cursor position relative to the container, at
// the time the drag started
window.dragStartX = null;
window.dragStartY = null;
var handleDragStart = function(element, xCursor, yCursor) {
window.dragStartX = xCursor - element.offsetLeft;
window.dragStartY = yCursor - element.offsetTop;
// disable transition animations, since we're starting a drag
$("#zoom-container").css("transition", "none");
};
var handleDragEnd = function() {
window.dragStartX = null;
window.dragStartY = null;
// remove the individual element's styling for transitions
// which brings back the stylesheet's default of animating.
$("#zoom-container").css("transition", "");
// keep track of the translate values we arrived at
window.translateY = window.lastTranslateY;
window.translateX = window.lastTranslateX;
};
var handleDragMove = function(xCursor, yCursor) {
var deltaX = xCursor - window.dragStartX;
var deltaY = yCursor - window.dragStartY;
var translateY = window.translateY + (deltaY / 2);
// the subtracted value here is to keep the letter in the center
var translateX = window.translateX + (deltaX / 2) - (0.25 * $("#inner-container")[0].clientWidth);
// fudge factor, probably because of percentage
// width/height problems. couldn't really trace down
// the underlying cause. hopefully the general approach
// is clear, though.
translateY -= 9;
translateX -= 4;
var innerContainer = $("#inner-container")[0];
// cap all values to prevent infinity scrolling off the page
if (translateY > 0.5 * innerContainer.clientHeight) {
translateY = 0.5 * innerContainer.clientHeight;
}
if (translateX > 0.5 * innerContainer.clientWidth) {
translateX = 0.5 * innerContainer.clientWidth;
}
if (translateY < -0.5 * innerContainer.clientHeight) {
translateY = -0.5 * innerContainer.clientHeight;
}
if (translateX < -0.5 * innerContainer.clientWidth) {
translateX = -0.5 * innerContainer.clientWidth;
}
// update the zoom container's translate values
// based on the original + delta, capped to the
// container's width and height.
$("#zoom-container").css("transform", "translate(" + (2*translateX) + "px, " + (2*translateY) + "px) scale(2)");
// keep track of the updated values for the next
// touchmove event.
window.lastTranslateX = translateX;
window.lastTranslateY = translateY;
};
// Drag start -- touch version
$("#container").on("touchstart", function(event) {
if (!window.zoomedIn) {
return true;
}
var xCursor = event.originalEvent.changedTouches[0].clientX;
var yCursor = event.originalEvent.changedTouches[0].clientY;
handleDragStart(this, xCursor, yCursor);
});
// Drag start -- mouse version
$("#container").on("mousedown", function(event) {
if (!window.zoomedIn) {
return true;
}
var xCursor = event.clientX;
var yCursor = event.clientY;
handleDragStart(this, xCursor, yCursor);
});
// Drag end -- touch version
$("#inner-container").on("touchend", function(event) {
if (!window.zoomedIn) {
return true;
}
handleDragEnd();
});
// Drag end -- mouse version
$("#inner-container").on("mouseup", function(event) {
if (!window.zoomedIn) {
return true;
}
handleDragEnd();
});
// Drag move -- touch version
$("#inner-container").on("touchmove", function(event) {
// prevent pull-to-refresh. could be smarter by checking
// if the page's scroll y-offset is 0, and even smarter
// by checking if we're pulling down, not up.
event.preventDefault();
if (!window.zoomedIn) {
return true;
}
var xCursor = event.originalEvent.changedTouches[0].clientX;
var yCursor = event.originalEvent.changedTouches[0].clientY;
handleDragMove(xCursor, yCursor);
});
// Drag move -- click version
$("#inner-container").on("mousemove", function(event) {
// prevent pull-to-refresh. could be smarter by checking
// if the page's scroll y-offset is 0, and even smarter
// by checking if we're pulling down, not up.
event.preventDefault();
// if we aren't dragging from anywhere, don't move
if (!window.zoomedIn || !window.dragStartX) {
return true;
}
var xCursor = event.clientX;
var yCursor = event.clientY;
handleDragMove(xCursor, yCursor);
});
var zoomInTo = function(element) {
console.log("applying zoom");
var top = element.offsetTop;
// the subtracted value here is to keep the letter in the center
var left = element.offsetLeft - (0.25 * $("#inner-container")[0].clientWidth);
var translateY = 0.5 * $("#zoom-container")[0].clientHeight - top;
var translateX = 0.5 * $("#zoom-container")[0].clientWidth - left;
$("#container").css("overflow", "scroll");
$("#zoom-container").css("transform", "translate(" + (2*translateX) + "px, " + (2*translateY) + "px) scale(2)");
window.translateY = translateY;
window.translateX = translateX;
window.zoomedIn = true;
}
var zoomOut = function() {
console.log("resetting zoom");
window.zoomedIn = false;
$("#zoom-container").css("transform", "");
$("#zoom-container").css("transition", "");
window.dragStartX = null;
window.dragStartY = null;
window.dragMoveJustHappened = null;
window.translateY = window.lastTranslateY;
window.translateX = window.lastTranslateX;
window.lastTranslateX = null;
window.lastTranslateY = null;
}
$(".box").click(function(event) {
var element = this;
var zoomContainer = $("#zoom-container");
if (!window.zoomedIn) {
zoomInTo(element);
}
});
$("#zoom-out").click(function(event) {
zoomOut();
});
CSS:
* {
margin: 0;
}
body,
html {
height: 100%;
}
#container {
height: 100%;
width: 50%;
margin: 0 auto;
}
#inner-container {
width: 100%;
height: 100%;
}
#zoom-container {
height: 100%;
width: 100%;
transition: transform 0.2s ease-in-out;
}
.box {
float: left;
width: 50%;
height: 50%;
color: white;
text-align: center;
display: block;
}
.red {
background: red;
}
.blue {
background: blue;
}
.green {
background: green;
}
.black {
background: black;
}
I pieced this together from another question (Move (drag/pan) and zoom object (image or div) in pure js), where the width and height are being changed. That doesn't quite apply in my case, because I need to zoom into a specific element on the page (with a lot boxes than in a 2x2 grid). The solution from that question (https://jsfiddle.net/j8kLz6wm/1/) shows the basic approach in pure JavaScript. If you have jQuery available, you can probably just use jquery.panzoom.
Update
I got stuck on scroll bars not showing all the time, so I need to investigating that part, so that code is commented out and instead I use a delay to move the clicked box into view.
Here is my fiddle demo, which I use to play with, to figure out how to solve the scroll bar issue.
Side note: In a comment made by #AVAVT, I would like to link to his post here, as that might help someone else, which I find as an interesting alternative in some cases.
(function(zoomed) {
$(".box").click(function(event) {
var el = this, elp = el.parentElement;
if (zoomed) {
zoomed = false;
$("#zoom-container").css({'transform': ''});
} else {
zoomed = true;
/* this zooms correct but show 1 or none scroll for B,C,D so need to figure out why
var tro = (Math.abs(elp.offsetTop - el.offsetTop) > 0) ? 'bottom' : 'top';
tro += (Math.abs(elp.offsetLeft - el.offsetLeft) > 0) ? ' right' : ' left';
$("#zoom-container").css({'transform-origin': tro, 'transform': 'scale(2)'});
*/
$("#zoom-container").css({'transform-origin': '0 0', 'transform': 'scale(2)'});
/* delay needed before scroll into view */
setTimeout(function() {
el.scrollIntoView();
},250);
}
});
})();
* { margin: 0; }
body, html { height: 100%; }
#container {
height: 100%;
width: 50%;
overflow: auto;
margin: 0 auto;
}
#zoom-container {
height: 100%;
width: 100%;
transition: all 0.2s ease-in-out;
}
.box {
float: left;
width: 50%;
height: 50%;
color: white;
text-align: center;
display: block;
}
.red {
background: red;
}
.blue {
background: blue;
}
.green {
background: green;
}
.black {
background: black;
}
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
<div id="container">
<div id="zoom-container">
<div class="box red">A</div>
<div class="box blue">B</div>
<div class="box green">C</div>
<div class="box black">D</div>
</div>
</div>

Stretched background stopped working

I am working on an experimental art site that involves a grid of images each scaled to the size of the viewport. The background for the page body should be one stretched image and it was working at one point but has stopped functioning. The background color shows and the image simply doesn't. However if the background-size CSS is turned off in Chrome inspector it shows up at it's own size positioned top and left...
I am guessing that having body contain a box which amounts to 5 viewports wide and 5 viewports tall is messing with what the body element's size is? Though allowing bg image to repeat didn't make it show up...
I resolved this by grabbing the screen width and height in the JavaScript and then setting background-size to those values like so:
$('body,html').css('background-size',the_width + 'px ' + the_height+'px');
But my question remains- why did the background-size:100% 100% stop working?
The page HTML looks like this only with 25 total divs and images.
<body>
<div id="box">
<div class="full" id="full_10">
<img src="home_tiles/10.jpg" width="800" height="600" title="10">
</div>
<div class="full" id="full_11">
<img src="home_tiles/11.jpg" width="800" height="600" title="11">
</div>
</div>
</body>
The CSS looks like this
* { padding: 0; margin: 0; }
html, body {
overflow:hidden;
background-color: #FF0000;
background-size: 100% 100%;
background-image:url(home_tiles/edge.jpg);
background-repeat:no-repeat;
}
img { display: block; }
#box {
position:absolute;
}
.full {
float:left;
}
The JavaScript sizing the images is
$(function() {
$('.full').hide();
var win = $(window),
fullscreen = $('.full'),
image = fullscreen.find('img'),
imageWidth = image.width(),
imageHeight = image.height(),
imageRatio = imageWidth / imageHeight;
var the_width;
var the_height;
var left_limit;
var right_limit;
function resizeImage() {
var winWidth = win.width(),
winHeight = win.height(),
winRatio = winWidth / winHeight;
if(winRatio > imageRatio) {
the_width = winWidth;
the_height = Math.round(winWidth / imageRatio);
} else {
the_width = Math.round(winHeight * imageRatio);
the_height = winHeight;
}
left_limit = the_width * -2;
right_limit = the_width * 2;
image.css({
width: the_width,
height: the_height
});
$('#box').css({
width: the_width * 5,
height: the_height * 5,
top: the_height * -2,
left: the_width * -2
});
}
win.bind({
load: function() {
resizeImage();
$('.full').show('slow');
},
resize: function() {
resizeImage();
}
});

Rotate image when scrolling

after using stackoverflow for plenty of help in the past I have a problem which will probably be easy for someone to solve…
I'm trying to rotate a background image when the user scrolls down the page, I have managed to get this far (with help from someone else's question and some helpful answers) but I need to slow down the rotation as its to fast. As far as I can tell I need to do something with the window height and use this to slow the rotation.
Heres my JSFiddle of how far I've got.
If anyone could help me out I'd be very grateful, my skills aren't quite up to scratch.
My code…
$(function() {
var rotation = 0,
scrollLoc = $(document).scrollTop();
$(window).scroll(function() {
var newLoc = $(document).scrollTop();
var diff = scrollLoc - newLoc;
rotation += diff, scrollLoc = newLoc;
var rotationStr = "rotate(" + rotation + "deg)";
$(".circle").css({
"-webkit-transform": rotationStr,
"-moz-transform": rotationStr,
"transform": rotationStr
});
});
})
CSS:
.container {
width:960px;
margin: 0 auto;
}
.circleWrap {
margin: 0 auto;
width:960px;
position:relative;
}
.circleContainer {
width: 970px;
position:fixed;
overflow:visible;
z-index:-50;
}
.circle{
background:url('http://www.wearerevolting.co.uk/dev/spin/moodring-col.jpg') no-repeat center;
width: 1772px;
height: 1772px;
margin-left: -400px;
}
.text {
z-index:50;
position:absolute;
height:2000px;
width:960px;
border:#000 thick solid;
}
<div class="container">
<div class="text">Content area</div>
</div>
<div class="circleWrap">
<div class="circleContainer">
<div class="circle"></div>
</div>
</div>
Cheers!
Change
var rotationStr = "rotate(" + rotation + "deg)";
to
var rotationStr = "rotate(" + rotation / 100 + "deg)";
where 100 is an arbitrary limiting value. Updated demo

Categories