Centering an image with absolute position (top, left) - javascript

I am using parametric equations to position images around a circle (How do I calculate a point on a circle’s circumference?)
I am doing this in less, using simple math:
// x,y position on circumference:
// x = a + r * cos(t)
// y = b + r * sin(t)
.position {
left: #a + ( #r * cos(#t) );
top: #b + ( #r * sin(#t) );
}
The trouble I have is that this positions the image by the top left corner, not the center of the image, so doesn't account for the visual offset of height and width this has. Trying to adjust by height/2, width/2 doesn't work as the angle of each image is different.
Is there an easy way to position an image this way so it is centred on x,y?

.position {
left: #a + ( #r * cos(#t) );
top: #b + ( #r * sin(#t) );
margin-left: -#r;
margin-top: -#r;
}
Instead of calculations you simply could have done this though:
top:50%;
left:50%;
position:absolute;
margin-left:-#r;
margin-top:-#r;
FIDDLE DEMO

Subtracting Out Half-Width/Height Does Work
You stated you tried half-width/height calculations in your attempt to center the image on the circumference of a circle at some angular reference (as I understand your question). It seems that should and does work. Check out this...
Example Fiddle
The circle and image colors are for visual reference, but the image positioning is done by:
LESS
//define circle position
#r: 100px;
#x: 175px;
#y: 150px;
.setImage(#w, #h, #a) {
//#a is angle from HORIZONTAL but moves clockwise
//(based on radians unless units are given)
width: #w;
height: #h;
left: (#x + ( #r * cos(#a) ) - (#w / 2));
top: (#y + ( #r * sin(#a) ) - (#h / 2));
}
.test1 {
.setImage(40px, 40px, -35deg);
}
.test2 {
.setImage(60px, 30px, -80deg);
}
.test3 {
.setImage(90px, 20px, -150deg);
}
.test4 {
.setImage(40px, 70px, -240deg);
}
.test5 {
.setImage(20px, 90px, -295deg);
}
CSS Output
.test1 {
width: 40px;
height: 40px;
left: 236.9152044288992px;
top: 72.64235636489539px;
}
.test2 {
width: 60px;
height: 30px;
left: 162.36481776669305px;
top: 36.5192246987792px;
}
.test3 {
width: 90px;
height: 20px;
left: 43.39745962155612px;
top: 90px;
}
.test4 {
width: 40px;
height: 70px;
left: 104.99999999999996px;
top: 201.60254037844385px;
}
.test5 {
width: 20px;
height: 90px;
left: 207.26182617406997px;
top: 195.630778703665px;
}
Works Even With Rotated Images
Assuming you set your images to have transform-origin: center center then it works to keep them on center even if the images are rotated at some angle.
See Rotated Image Example Fiddle

Related

CSS position elements along ring of a circle [duplicate]

How can I position several <img> elements into a circle around another and have those elements all be clickable links as well? I want it to look like the picture below, but I have no idea how to achieve that effect.
Is this even possible?
2020 solution
Here's a more modern solution I use these days.
I start off by generating the HTML starting from an array of images. Whether the HTML is generated using PHP, JS, some HTML preprocessor, whatever... this matters less as the basic idea behind is the same.
Here's the Pug code that would do this:
//- start with an array of images, described by url and alt text
- let imgs = [
- {
- src: 'image_url.jpg',
- alt: 'image alt text'
- } /* and so on, add more images here */
- ];
- let n_imgs = imgs.length;
- let has_mid = 1; /* 0 if there's no item in the middle, 1 otherwise */
- let m = n_imgs - has_mid; /* how many are ON the circle */
- let tan = Math.tan(Math.PI/m); /* tangent of half the base angle */
.container(style=`--m: ${m}; --tan: ${+tan.toFixed(2)}`)
- for(let i = 0; i < n_imgs; i++)
a(href='#' style=i - has_mid >= 0 ? `--i: ${i}` : null)
img(src=imgs[i].src alt=imgs[i].alt)
The generated HTML looks as follows (and yes, you can write the HTML manually too, but it's going to be a pain to make changes afterwards):
<div class="container" style="--m: 8; --tan: 0.41">
<a href='#'>
<img src="image_mid.jpg" alt="alt text"/>
</a>
<a style="--i: 1">
<img src="first_img_on_circle.jpg" alt="alt text"/>
</a>
<!-- the rest of those placed on the circle -->
</div>
In the CSS, we decide on a size for the images, let's say 8em. The --m items are positioned on a circle and it's if they're in the middle of the edges of a polygon of --m edges, all of which are tangent to the circle.
If you have a hard time picturing that, you can play with this interactive demo which constructs the incircle and circumcircle for various polygons whose number of edges you pick by dragging the slider.
This tells us that the size of the container must be twice the radius of the circle plus twice half the size of the images.
We don't yet know the radius, but we can compute it if we know the number of edges (and therefore the tangent of half the base angle, precomputed and set as a custom property --tan) and the polygon edge. We probably want the polygon edge to be a least the size of the images, but how much we leave on the sides is arbitrary. Let's say we have half the image size on each side, so the polygon edge is twice the image size. This gives us the following CSS:
.container {
--d: 6.5em; /* image size */
--rel: 1; /* how much extra space we want between images, 1 = one image size */
--r: calc(.5*(1 + var(--rel))*var(--d)/var(--tan)); /* circle radius */
--s: calc(2*var(--r) + var(--d)); /* container size */
position: relative;
width: var(--s); height: var(--s);
background: silver /* to show images perfectly fit in container */
}
.container a {
position: absolute;
top: 50%; left: 50%;
margin: calc(-.5*var(--d));
width: var(--d); height: var(--d);
--az: calc(var(--i)*1turn/var(--m));
transform:
rotate(var(--az))
translate(var(--r))
rotate(calc(-1*var(--az)))
}
img { max-width: 100% }
See the old solution for an explanation of how the transform chain works.
This way, adding or removing an image from the array of images automatically arranges the new number of images on a circle such that they're equally spaced out and also adjusts the size of the container. You can test this in this demo.
OLD solution (preserved for historical reasons)
Yes, it is very much possible and very simple using just CSS. You just need to have clear in mind the angles at which you want the links with the images (I've added a piece of code at the end just for showing the angles whenever you hover one of them).
You first need a wrapper. I set its diameter to be 24em (width: 24em; height: 24em; does that), you can set it to whatever you want. You give it position: relative;.
You then position your links with the images in the center of that wrapper, both horizontally and vertically. You do that by setting position: absolute; and then top: 50%; left: 50%; and margin: -2em; (where 2em is half the width of the link with the image, which I've set to be 4em - again, you can change it to whatever you wish, but don't forget to change the margin in that case).
You then decide on the angles at which you want to have your links with the images and you add a class deg{desired_angle} (for example deg0 or deg45 or whatever). Then for each such class you apply chained CSS transforms, like this:
.deg{desired_angle} {
transform: rotate({desired_angle}) translate(12em) rotate(-{desired_angle});
}
where you replace {desired_angle} with 0, 45, and so on...
The first rotate transform rotates the object and its axes, the translate transform translates the object along the rotated X axis and the second rotate transform brings back the object into position.
The advantage of this method is that it is flexible. You can add new images at different angles without altering the current structure.
CODE SNIPPET
.circle-container {
position: relative;
width: 24em;
height: 24em;
padding: 2.8em;
/*2.8em = 2em*1.4 (2em = half the width of a link with img, 1.4 = sqrt(2))*/
border: dashed 1px;
border-radius: 50%;
margin: 1.75em auto 0;
}
.circle-container a {
display: block;
position: absolute;
top: 50%; left: 50%;
width: 4em; height: 4em;
margin: -2em;
}
.circle-container img { display: block; width: 100%; }
.deg0 { transform: translate(12em); } /* 12em = half the width of the wrapper */
.deg45 { transform: rotate(45deg) translate(12em) rotate(-45deg); }
.deg135 { transform: rotate(135deg) translate(12em) rotate(-135deg); }
.deg180 { transform: translate(-12em); }
.deg225 { transform: rotate(225deg) translate(12em) rotate(-225deg); }
.deg315 { transform: rotate(315deg) translate(12em) rotate(-315deg); }
<div class='circle-container'>
<a href='#' class='center'><img src='image.jpg'></a>
<a href='#' class='deg0'><img src='image.jpg'></a>
<a href='#' class='deg45'><img src='image.jpg'></a>
<a href='#' class='deg135'><img src='image.jpg'></a>
<a href='#' class='deg180'><img src='image.jpg'></a>
<a href='#' class='deg225'><img src='image.jpg'></a>
<a href='#' class='deg315'><img src='image.jpg'></a>
</div>
Also, you could further simplify the HTML by using background images for the links instead of using img tags.
EDIT: example with fallback for IE8 and older (tested in IE8 and IE7)
Here is the easy solution without absolute positioning:
.container .row {
margin: 20px;
text-align: center;
}
.container .row img {
margin: 0 20px;
}
<div class="container">
<div class="row">
<img src="https://ssl.gstatic.com/s2/oz/images/faviconr2.ico" alt="" width="64" height="64">
<img src="https://ssl.gstatic.com/s2/oz/images/faviconr2.ico" alt="" width="64" height="64">
</div>
<div class="row">
<img src="https://ssl.gstatic.com/s2/oz/images/faviconr2.ico" alt="" width="64" height="64">
<img src="https://ssl.gstatic.com/s2/oz/images/faviconr2.ico" alt="" width="64" height="64">
<img src="https://ssl.gstatic.com/s2/oz/images/faviconr2.ico" alt="" width="64" height="64">
</div>
<div class="row">
<img src="https://ssl.gstatic.com/s2/oz/images/faviconr2.ico" alt="" width="64" height="64">
<img src="https://ssl.gstatic.com/s2/oz/images/faviconr2.ico" alt="" width="64" height="64">
</div>
</div>
http://jsfiddle.net/mD6H6/
Using the solution proposed by #Ana:
transform: rotate(${angle}deg) translate(${radius}px) rotate(-${angle}deg)
I created the following jsFiddle that places circles dynamically using plain JavaScript (jQuery version also available).
The way it works is rather simple:
document.querySelectorAll( '.ciclegraph' ).forEach( ( ciclegraph )=>{
let circles = ciclegraph.querySelectorAll( '.circle' )
let angle = 360-90, dangle = 360 / circles.length
for( let i = 0; i < circles.length; ++i ){
let circle = circles[i]
angle += dangle
circle.style.transform = `rotate(${angle}deg) translate(${ciclegraph.clientWidth / 2}px) rotate(-${angle}deg)`
}
})
.ciclegraph {
position: relative;
width: 500px;
height: 500px;
margin: calc(100px / 2 + 0px);
}
.ciclegraph:before {
content: "";
position: absolute;
top: 0; left: 0;
border: 2px solid teal;
width: calc( 100% - 2px * 2);
height: calc( 100% - 2px * 2 );
border-radius: 50%;
}
.ciclegraph .circle {
position: absolute;
top: 50%; left: 50%;
width: 100px;
height: 100px;
margin: calc( -100px / 2 );
background: teal;
border-radius: 50%;
}
<div class="ciclegraph">
<div class="circle"></div>
<div class="circle"></div>
<div class="circle"></div>
<div class="circle"></div>
<div class="circle"></div>
<div class="circle"></div>
</div>
Building off #Ana's excellent answer, I created this dynamic version that allows you to add and remove elements from the DOM and maintain proportionate spacing between the elements - check out my fiddle: https://jsfiddle.net/skwidbreth/q59s90oy/
var list = $("#list");
var updateLayout = function(listItems) {
for (var i = 0; i < listItems.length; i++) {
var offsetAngle = 360 / listItems.length;
var rotateAngle = offsetAngle * i;
$(listItems[i]).css("transform", "rotate(" + rotateAngle + "deg) translate(0, -200px) rotate(-" + rotateAngle + "deg)")
};
};
$(document).on("click", "#add-item", function() {
var listItem = $("<li class='list-item'>Things go here<button class='remove-item'>Remove</button></li>");
list.append(listItem);
var listItems = $(".list-item");
updateLayout(listItems);
});
$(document).on("click", ".remove-item", function() {
$(this).parent().remove();
var listItems = $(".list-item");
updateLayout(listItems);
});
#list {
background-color: blue;
height: 400px;
width: 400px;
border-radius: 50%;
position: relative;
}
.list-item {
list-style: none;
background-color: red;
height: 50px;
width: 50px;
position: absolute;
top: 50%;
left: 50%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<ul id="list"></ul>
<button id="add-item">Add item</button>
Here is a version I made in React from the examples here.
CodeSandbox Example
import React, { useRef, useEffect } from "react";
import "./styles.css";
export default function App() {
const graph = useRef(null);
useEffect(() => {
const ciclegraph = graph.current;
const circleElements = ciclegraph.childNodes;
let angle = 360 - 90;
let dangle = 360 / circleElements.length;
for (let i = 0; i < circleElements.length; i++) {
let circle = circleElements[i];
angle += dangle;
circle.style.transform = `rotate(${angle}deg) translate(${ciclegraph.clientWidth /
2}px) rotate(-${angle}deg)`;
}
}, []);
return (
<div className="App">
<div className="ciclegraph" ref={graph}>
<div className="circle" />
<div className="circle" />
<div className="circle" />
<div className="circle" />
<div className="circle" />
<div className="circle" />
</div>
</div>
);
}
You can certainly do it with pure css or use JavaScript. My suggestion:
If you already know that the images number will never change just calculate your styles and go with plain css (pros: better performances, very reliable)
If the number can vary either dynamically in your app or just may vary in the future go with a Js solution (pros: more future-proof)
I had a similar job to do, so I created a script and open sourced it here on Github for anyone who might need it. It just accepts some configuration values and simply outputs the CSS code you need.
If you want to go for the Js solution here's a simple pointer that can be useful to you. Using this html as a starting point being #box the container and .dot the image/div in the middle you want all your other images around:
Starting html:
<div id="box">
<div class="dot"></div>
<img src="my-img.jpg">
<!-- all the other images you need-->
</div>
Starting Css:
#box{
width: 400px;
height: 400px;
position: relative;
border-radius: 100%;
border: 1px solid teal;
}
.dot{
position: absolute;
border-radius: 100%;
width: 40px;
height: 40px;
left: 50%;
top: 50%;
margin-left: -20px;
margin-top: -20px;
background: rebeccapurple;
}
img{
width: 40px;
height: 40px;
position: absolute;
}
You can create a quick function along these lines:
var circle = document.getElementById('box'),
imgs = document.getElementsByTagName('img'),
total = imgs.length,
coords = {},
diam, radius1, radius2, imgW;
// get circle diameter
// getBoundingClientRect outputs the actual px AFTER transform
// using getComputedStyle does the job as we want
diam = parseInt( window.getComputedStyle(circle).getPropertyValue('width') ),
radius = diam/2,
imgW = imgs[0].getBoundingClientRect().width,
// get the dimensions of the inner circle we want the images to align to
radius2 = radius - imgW
var i,
alpha = Math.PI / 2,
len = imgs.length,
corner = 2 * Math.PI / total;
// loop over the images and assign the correct css props
for ( i = 0 ; i < total; i++ ){
imgs[i].style.left = parseInt( ( radius - imgW / 2 ) + ( radius2 * Math.cos( alpha ) ) ) + 'px'
imgs[i].style.top = parseInt( ( radius - imgW / 2 ) - ( radius2 * Math.sin( alpha ) ) ) + 'px'
alpha = alpha - corner;
}
You can see a live example here
There is no way to magically place clickable items in a circle around another element with CSS.
The way how I would do this is by using a container with position:relative;. And then place all the elements with position:absolute; and using top and left to target it's place.
Even though you haven't placed jquery in your tags it might be best to use jQuery / javascript for this.
First step is placing your center image perfectly in the center of the container using position:relative;.
#centerImage {
position:absolute;
top:50%;
left:50%;
width:200px;
height:200px;
margin: -100px 0 0 -100px;
}
After that you can place the other elements around it by using an offset() of the centerImage minus the offset() of the container. Giving you the exact top and left of the image.
var left = $('#centerImage').offset().left - $('#centerImage').parent().offset().left;
var top = $('#centerImage').offset().top - $('#centerImage').parent().offset().top;
$('#surroundingElement1').css({
'left': left - 50,
'top': top - 50
});
$('#surroundingElement2').css({
'left': left - 50,
'top': top
});
$('#surroundingElement3').css({
'left': left - 50,
'top': top + 50
});
What I've done here is placing the elements relative to the centerImage. Hope this helps.
You could do it like this: fiddle
Don't mind the positioning, its a quick example
The first step is to have 6 long columnar boxes:
The second step is to use position: absolute and move them all into the middle of your container:
And now rotate them around the pivot point located at the bottom center. Use :nth-child to vary rotation angles:
div {
transform-origin: bottom center;
#for $n from 0 through 7 {
&:nth-child(#{$n}) {
rotate: (360deg / 6) * $n;
}
}
Now all you have to do is to locate your images at the far end of every column, and compensate the rotation with an anti-rotation :)
Full source:
<div class="flower">
<div class="petal">1</div>
<div class="petal">2</div>
<div class="petal">3</div>
<div class="petal">4</div>
<div class="petal">5</div>
<div class="petal">6</div>
</div>
.flower {
width: 300px;
height: 300px;
// We need a relative position
// so that children can have "position:abolute"
position: relative;
.petal {
// Make sure petals are visible
border: 1px solid #999;
// Position them all in one point
position: absolute; top: 0; left: 50%;
display: inline-block;
width: 30px; height: 150px;
// Rotation
transform-origin: bottom center;
#for $n from 0 through 7 {
&:nth-child(#{$n}) {
// Petal rotation
$angle: (360deg / 6) * $n;
rotate: $angle;
// Icon anti-rotation
.icon { rotate: -$angle; }
}
}
}
}
See CodePen

How to adjust the mouse position after rotating an object?

I am trying to create an eye that follows cursor movement.
I got the horizontal and vertical coordinate of the mouse and the browser width and height.
Everything works perfectly. Except that I used rotate(45 deg) on the design of the eye so now the ball is not moving in the right position.
I was thinking about a math equation that finds the distance between the old and new coords, but I am not sure how to implement it.
Here is the full code:
https://jsfiddle.net/Mr_MeS/3ym6kuec/3/
so this is the .eye where its rotated
.eye {
width: 37.5px;
height: 37.5px;
background: white;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%) rotate(45deg);
border-radius: 75% 0;
overflow: hidden;
cursor: pointer;
}
.ball {
width: 7.5px;
height: 7.5px;
background: #222f3e;
border-radius: 50%;
border: 5px solid #576574;
position: relative;
top: 50%;
left: 50%;
}
and here is the JS that does the work and needs to be edited.
var balls = document.getElementsByClassName("ball");
document.onmousemove = function () {
var x = event.clientX * 100 / window.innerWidth + "%";
var y = event.clientY * 100 / window.innerHeight + "%";
//event.clientX => get the horizontal coordinate of the mouse
//event.clientY => get the Vertical coordinate of the mouse
//window.innerWidth => get the browser width
//window.innerHeight => get the browser height
for (var i = 0; i < 2; i++) {
balls[0].style.left = x;
balls[0].style.top = y;
balls[0].style.transform = "translate(-" + x + ",-" + y + ")";
}
}
Now, if I remove the rotation from the .eye, it works perfectly, expect that the whole shape doesn't look to be in position.
If I keep the 45deg rotation, the shape is good, but the ball moves wrongly.
You could try to put the eye-background (the white part that needs to rotate 45 degrees) into a div (or pseudo-element) that's inside the .eye element. In that way you don't need to rotate the container element, so the coordination of the ball element stays the same.
Another point, why are you using that for-loop? I think running the code once will be sufficient :)
EDIT: I've been playing around with your example a bit and fixed it. What happens is that if you rotate an element, the direction in which things will transform (and top/left positioning) will also change. So moving the element 10px to the left, will go 10px to the left, under a 45 degree angle, because it's rotated 45 degrees.
What I did now was to put an element (.inner) inside the eye div, which I gave a counter-rotation of -45 degrees. In this way, the container element of the ball has the correct orientation again, which fixes the problem: https://jsfiddle.net/bxprjvgL/
HTML:
<div class="eye">
<div class="inner">
<div class="shut"><span></span></div>
<div class="ball"></div>
</div>
</div>
CSS:
.inner {
width: 100%;
height: 100%;
transform: rotate(-45deg);
}

How to "glue" elements to resizable image?

I have image with width: 100%; height: auto; and on this image are other elements with position: absolute; left: x; top: x; (it's a game).
When I was resizing the page, elements weren't moving (it was messing up), so I wrote this:
// on start
var img = document.getElementById('world_image');
startImageSize.w = img.clientWidth;
startImageSize.h = img.clientHeight;
actImageSize.w = startImageSize.w;
actImageSize.h = startImageSize.h;
// on resize
var img = document.getElementById('world_image');
actImageSize.w = img.clientWidth;
actImageSize.h = img.clientHeight;
// update (each tick)
$("#cr_" + this.ID).animate({
"left" : (this.x - ((startImageSize.w - actImageSize.w) / 2)) + "px",
"top" : (this.y - ((startImageSize.h - actImageSize.h) / 2)) + "px"
}, speed);
But it's not working corretly, here is short GIF representing what is happening:
A "red point" is moving faster than it shoud be.
// EDDIT! JSFiddle with whole project https://jsfiddle.net/BrunonDEV/18mqyd8r/1/
What am I doing wrong?
I wouldn't try to reposition those in JS - it's slow, makes resizing janky, and chews the javascript cycles you'll need for actually running your game, and it's not necessary anyway. Why not just set your dot's position in %, like this:
.map {
background: #68B1FF url('https://upload.wikimedia.org/wikipedia/commons/5/5e/BlankMap-World-Sovereign_Nations.svg') center top no-repeat;
background-size: contain;
position: relative;
height: 0;
padding-top: 51.2%; /* The original map image is 1104 x 566px. This is the aspect ratio as a percentage of height to width */
width: 100%;
}
.marker {
border-radius: 50%;
width: 1vw; /* These allow the markers to scale with the map */
height: 1vw;
background: red;
min-height: 8px;
max-height: 16px;
min-width: 8px;
max-width: 16px;
position: absolute;
}
<div class="map">
<div class="marker" style="top: 20%; left: 33%;"></div>
</div>
One of the important pieces here is fixed aspect ratio boxes in CSS - if you set height to 0, and padding-top (or bottom) to a percentage, the padding height is calculated as a percentage of the width, not the height as you might expect.
For bonus points, you should use an SVG map image - then it'll scale cleanly, too.

Make div fly with animation to another DOM position

I am moving an <img> element (the octopus) from the large gray <div> above (#large) to the small orange <div> below (#small) using
$(document).on("click", "#large > img", function() {
$(this).appendTo("#small");
});
This works great but I want it to transition smoothly and to 'fly' over so it will slowly interpolate its coordinates and size.
I tried adding a CSS transition
img { transition: all 3s; }
to my <img>, but that won't work as the image is readded to the DOM and not moved.
How can such animation be established?
JS Fiddle
Using the jQuery .append method won't allow you to animate the element between the 2 states.
Here is an example with an animation using CSS transition and the scale() function. This example also uses the transform-origin property to change the position the of the image on the "big" state. Fiddle here.
$(document).on("click", "img", function() {
$(this).toggleClass("big");
});
div {
margin: 20px;
padding: 10px;
}
#large {
width: 600px;
height: 400px;
background-color: gray;
}
#small {
width: 120px;
height: 90px;
background-color: orange;
}
img {
width: 100%;
height: 100%;
transition: transform .3s ease-out;
transform-origin: 0 129px;
}
img.big {
transform: scaleX(5) scaleY(4.4);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="large">
</div>
<div id="small">
<img src="https://ak.picdn.net/assets/cms/5bb580387901a83212e3028ab5a2fa8fb1153d7b-img_offset_2x.jpg" />
</div>
Note that :
you will need to add vendor prefixes to the transition, transform and transform-origin properties depending on the browsers you need to support.
this technique relies on the fact you are using hard values (in pixels). It would be possible to make this responsive (using percent values for widths, margins and paddings) but it will need more calculations.
i made a responsive solution ( so i think ) using JQ . check it out below or in jsFiddle
first i cached all the necessary selectors for cleaner and concise code .
the -20 is because of the div { margin-top:20px}`
there i calculated the TOP offset of both divs in relation to the document, then got the width and height of the small div
in the click function first i got the image's top offset so i could compare that with the #small's offset .
so if the image's distance to top is smaller than the #small's distance to top, it means that the img is in the #large div and so i move it using transform:translate giving it an Y-axis value equal to the TOP offset of the #small Div, so the img offset.top ( iOffset ) will become equal to the #small offset.top ( sOffset )
also adding width and height of the #small div to the image
else ( if iOffset is = or bigger than sOffset ) then it means that the image is not in the large div, so i need to translate it back to the offset of the #large div and add width:100% and height:100%
hope i got it right and explained correctly.
let me know if it helps
var Large = $("#large"),
Small = $("#small"),
lOffset = $(Large).offset().top - 20 + 'px',
sOffset = $(Small).offset().top - 20 + 'px',
sWidth = $(Small).width(),
sHeight = $(Small).height()
$(document).on("click", "img", function() {
var iOffset = $(this).offset().top + 'px'
if (iOffset < sOffset) {
$(this).css('transform', 'translate(0,' + sOffset + ')')
.width(sWidth).height(sHeight)
} else {
$(this).css('transform', 'translate(0,' + lOffset + ')')
.width("100%").height("100%")
}
})
div {
margin: 20px;
padding: 10px;
}
#large {
width: 600px;
height: 400px;
background-color: gray;
}
#small {
width: 120px;
height: 90px;
background-color: orange;
}
img {
width: 100%;
height: 100%;
transition: 5s;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="large">
<img src="https://ak.picdn.net/assets/cms/5bb580387901a83212e3028ab5a2fa8fb1153d7b-img_offset_2x.jpg" />
</div>
<div id="small">
</div>
You need to compute the current dimensions of the image, the target dimensions, and calculate the needed transform.
To make it easier, I will calculate the transform needed to make the new element (the cloned one) look like it is still at the current position.
Later, a standard animation (that just resets scale and position) will do the trick.
I avoided using jQuery so the solution is easier to port
function func (target) {
var image = document.getElementById('image');
var current = image.parentNode;
var rectImage = current.getBoundingClientRect();
var rectTarget = target.getBoundingClientRect();
evalRect (rectImage);
evalRect (rectTarget);
var scaleX = rectImage.width / rectTarget.width;
var scaleY = rectImage.height / rectTarget.height;
var translateX = rectImage.centerX - rectTarget.centerX;
var translateY = rectImage.centerY - rectTarget.centerY;
var dup = image.cloneNode();
var scale = 'scale(' + scaleX + ', ' + scaleY + ') ';
var translate = 'translate(' + translateX + 'px, ' + translateY + 'px) ';
target.appendChild(dup);
dup.style.transform = translate + scale;
current.removeChild(image);
}
function evalRect (rect) {
rect.centerX = rect.left + rect.width * 0.5;
rect.centerY = rect.top + rect.height * 0.5;
}
.container {
border: solid 1px black;
position: relative;
display: inline-block;
}
#container1 {
width: 200px;
height: 100px;
}
#container2 {
width: 400px;
height: 200px;
}
#container3 {
width: 200px;
height: 200px;
}
#image {
background: linear-gradient(45deg, yellow, tomato);
width: 100%;
height: 100%;
position: absolute;
left: 0px;
top: 0px;
animation: adjust 1s forwards;
}
#keyframes adjust {
to {transform: translate(0px, 0px);}
}
<div id="container1" class="container" onclick="func(this)">click me
<div id="image"></div>
</div>
<div id="container2" class="container" onclick="func(this)">click me</div>
<div id="container3" class="container" onclick="func(this)">click me</div>
appendto do not accept animations, but this question maybe helpful for you
appendTo() animation
Just add a transition and change the size and position to match the target. On the transitionend event, append the image to the target element.
// when transition completes
$('img').on('webkitTransitionEnd otransitionend oTransitionEnd msTransitionEnd transitionend', function(){
// place in container
$('#target').append($('img'));
// set to corner of container
$('img').css({
top: '0',
left: '0'
});
});
// position in corner of target and make size the same
$('img').css({
position: 'absolute',
top: $('#target').offset().top + 'px',
left: $('#target').offset().left + 'px',
height: $('#target').css('height'),
width: $('#target').css('width')
});
#target {
height: 150px;
width: 150px;
border: 1px solid grey;
position: absolute;
top: 350px;
left: 5px;
z-index: 1;
}
img {
position: absolute;
top: 0;
left: 5px;
transition: all 1s;
height: 300px;
width: 300px;
z-index: 5;
}
<script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script>
<img src="https://placeholdit.imgix.net/~text?txtsize=33&txt=300%C3%97300&w=300&h=300" />
<div id="target">
</div>

jQuery X-Ray Effect to Reveal Data Points

I have a client who wants to have an X-Ray effect that reveals clickable data points. A slider would be used to move a viewing window over an image, that would reveal an x-ray, or secondary image as the slider is moved. I've adapted Eli Kirk's X-Ray effect (http://elikirk.com/2013/12/02/draggable-x-ray-effect-using-css-javascript/) to get what I have so far: http://jsfiddle.net/xfxLx/3/. The jQuery UI portion of it is easy enough:
var artWidth = 300;
$(document).ready(function() {
$('.xraySlider').slider({
slide: function(e, ui) {
var newLeft = (ui.value / 100) * (artWidth - 100);
$('.xrayWindow').css({'background-position': (newLeft * -1) + 'px 0px', "left": newLeft + "px" });
}
});
});
The problem I'm having is making clickable data points that would be revealed by the window as it is slid across the main image. The data points would be fairly simple shapes (like, say, a black circle), that the user could click on once revealed by the x-ray window, to reveal a popup with more info. I've beat my head against the wall trying to come up with a workable solution (if this wasn't bad enough, it all has to work in IE7, so I've ruled out canvas as well).
If this effect won't work under the confines listed (which I've told them might be the case, since I have yet to come up with a viable solution), that's fine, but I just want to make sure I'm not missing anything.
I have changed yoput HTML, setting an inner element to the xray, that will hold the points
<div class="artifact-hold">
<div class="artifact">
<div class="xrayUpper"></div>
<div class="xrayWindow">
<div class="innerXray">
<div class="point" id="brain"></div>
<div class="point" id="heart"></div>
</div>
</div>
<br />
<div class="xraySlider"></div>
</div>
</div>
Then, the JavaScript changes slightly
var artWidth = 300;
$(document).ready(function() {
$('.xraySlider').slider({
slide: function(e, ui) {
var newLeft = (ui.value / 100) * (artWidth - 100);
$('.xrayWindow').css({"left": newLeft + "px" });
$('.innerXray').css({"left": -newLeft + "px" });
}
});
});
And CSS is changed to make the xray clip the contents (with overflow hidden), and the inner has the background image instead of the xraywindow. also, some styling to the points.
.innerXray {
width: 300px;
height: 490px;
position: absolute;
background: url(http://s21.postimg.org/tpg6me1vb/bones.jpg) no-repeat;
background-position: 0px 0px;
}
.point {
position: absolute;
width: 8px;
height: 8px;
border-radius: 50%;
background-color: red;
}
#heart {
left: 150px;
top: 130px;
}
#brain {
left: 150px;
top: 30px;
}
.xrayWindow {
width: 100px;
height: 490px;
border: 2px solid rgba(255,255,255,0.5);
position: absolute;
top: 0px;
left: 0px;
overflow: hidden;
}
result

Categories

Resources