How to smoothly animate position & size of an rounded rectangle? - javascript

I am implementing a "pane" view component. Similar to IntelliJ or VSCode, where each pane can be rearranged into different rows and columns. The drag-and-drop rearrange action requires a preview animation: a box that animates around the screen, showing where the new pane would be inserted if the action was finished.
Basically, I need an absolutely-positioned rounded rectangle that can smoothly animate around the screen. Ideally this would be GPU-accelerated.
My attempts:
Attempt no. 1
I simply created a <div> element and animated the height, width, top and left values. This works, and allows all other CSS effects to work on the rectangle, like borders and rounded edges. However, it's not very fast. Animating the position and size directly is recommended against because it forces a reflow on each frame.
Attempt no. 2
Instead, I created 1px by 1px colored <div>, and set its size and position by editing it's transform CSS property. This is super smooth because it uses the GPU-accelerated transform property. However, it comes with a downside: I cannot style the <div>. I cannot use border or border-radius, otherwise they become distorted by the scale transformation.
Ideas
Since a rectangle is a simple shape, could we generate an svg and interpolate between different positions? If this happens within the viewBox, would it be smooth? I'm unsure about this, because I don't have much experience with SVGs.
My question – how can I smoothly animate a div around the screen, which is styled with a border or border-radius?
I could live without the border, but the border-radius is strongly desired.

I am not entirely sure I have fully understood the problem as I am unable to recreate it in this situation:
This snippet uses transform scale and transform translate to animate an element. Evertyhing is calculated with vmin used as the basic unit just so you'll see the same aspect ratios whatever device/viewport you are using.
On my laptop the GPU usage is a pretty consistent 13%, the transforms are smooth and I can't see any distortion. So is there perhaps in the original code some absolutely defined unit used that doesn't for example scale correctly?
* {
margin: 0;
padding: 0;
}
body {
width: 100vw;
height: 100vh;
}
.container {
--containerw: 80vmin;
--containerh: 60vmin;
width: var(--containerw);
height: var(--containerh);
position: relative;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
position: relative;
background-color: pink;
}
.test {
--startleft: 10;
/* where it starts (within the container as a %) */
--starttop: 10;
--endleft: 70;
/* where you want it to go to (within the container as a %) */
--endtop: 70;
--scalex: 4;
/* how much you want it to grow */
--scaley: 2;
--w: 10%;
/* its width */
--h: 10%;
/* its height */
width: var(--w);
height: var(--h);
border-radius: 1vmin;
border-width: 0.2vmin;
border-style: solid;
background-color: cyan;
animation: move 10s infinite linear;
position: absolute;
box-sizing: border-box;
}
#keyframes move {
0%,
100% {
transform: scale(1, 1) translate(calc(var(--startleft) * var(--containerw) / 100), calc(var(--starttop) * var(--containerh) / 100));
}
50% {
transform: scale(var(--scalex), var(--scaley)) translate(calc(var(--endleft) * var(--containerw) / 100 / var(--scalex)), calc(var(--endtop) * var(--containerh) / 100 / var(--scaley)));
}
}
<div class="container">
<div class="test"></div>
</div>

I figured out a fix! This allows smooth animations (using GPU-accelerated transformations) for a <div/> with rounded corners and a border, without any stretching.
It's based on the "border image" concept. Instead of animating one <div/>, we can animate 9 different divs, each representing a slice of the rectangle.
Top left corner
Top center rectangle
Top right corner
Middle left rectangle
Middle center rectangle
Middle right rectangle
Bottom left corner
Bottom center rectangle
Bottom right corner
The corners don't need to be scaled, only translated. This prevents any stretching. The rectangle edges are scaled in line with the border, and so it doesn't stretch a solid border.

Related

Is it possible to make a div work like how a "layer mask" would? [duplicate]

I have a background image that has background-size:cover; applied to it and then a series of divs overlaid which I would like to become individual clipping masks.
I've looked at the feature clip: rect(20px, 20px, 20px, 20px,); however as the divs are brought in through a CMS system, it will be inappropriate to define set sizes.
Is there a way of setting the div with a clipping mask property so that it clips the image anywhere the div is placed on the page?
I don't particularly want to use an image overlay either as this site will be responsive.
The clip-path CSS property can be applied to all HTML elements, SVG graphic elements and SVG container elements:
http://www.html5rocks.com/en/tutorials/masking/adobe/
If I understood correctly, you're simply looking for an overlay that will resize with the screen size, and the div with the background image?
In that case, if possible, why not simply append these divs INSIDE the div that needs clipping, like this. For this sample purpose I only used one div with a transparent background and a border applied to it. If you need to clip the image in a non-rectangular shape, you will need more divs (ex. for parallelogram, diamond, triangle shape, you'll need at least 2).
Also, sadly CSS doesn't allow for % borders, but I think this example is
You can also do it the other way around and place your img div inside the clipper divs; just a matter of what fits best...
body, html {
/* necessary for sizing children in % */
width: 100%;
height: 100%;
}
#tobeClipped {
width: 80%;
height: 40%;
position: relative;
background-image: url('http://cdn.theatlantic.com/static/infocus/ngpc112812/s_n01_nursingm.jpg');
background-size: cover;
}
#tobeClipped>div {
position: absolute;
}
#clippers {
width: 100%;
height: 100%;
border: 20px solid grey;
border-left-width: 100px;
box-sizing: border-box;
}
<div id="tobeClipped">
<div id="clippers"></div>
</div>
Please do clarify if this was not at all what you were looking for.

How to manually set overflow size on parent container when using CSS transform on child?

I understand that CSS transforms don't affect the effective size of an element, just its visual presentation. The following posts discuss this:
CSS Scale transform on child not affecting parent size
CSS transform: scale does not change DOM size?
I also see the following discussions that don't quite discuss overflow distance:
How can I wrap a container around its css-transformed contents?
width/height after transform
I am trying to wrap an element which has been scaled inside another element with overflow set to scroll.
The issue is that because CSS scaling does not affect the actual size of an element, just its visual presentation the scroll overflow is set to the original dimensions of the element, which is either too large or too small
Is there a method of explicitly setting the overflow distance on the parent to work around this issue? That might allow me to do something like setting the overflow height to the child height * scale and the width to child width * scale on the parent.
I expect the actual scaling value to change via user input, dynamically resizing the element on the fly.
Below is an example snippet of the issue in action.
.parent {
overflow: scroll;
height: 500px;
width: 500px;
background: black;
}
.child {
background-image: url("https://i.redd.it/7ifkx5z39b631.jpg");
transform: scale(0.25, 0.25);
transform-origin: top left;
height: 7000px;
width: 4900px;
}
<div class="parent">
<div class="child">
</div>
</div>
Well you could use a pseudo element inside the container...
.parent:before {
content: '';
position: relative;
z-index: -1;
width: calc(4900px * 0.25);
height: calc(7000px * 0.25);
}
That should force the overflow. I'm using a negative z-index to make sure it doesn't interact with the content.
Note: if the scaling is dynamic it's likely easier to actually create an empty element (pseudo-classes are difficult to control via JS) and then dynamically control the height/width using Javascript.
<div class="parent">
<div class="spacer"></div>
<div class="child">
</div>
</div>
And CSS
.spacer {
content: '';
position: relative;
z-index: -1;
width: calc(4900px * 0.25);
height: calc(7000px * 0.25);
}
Edit: Oops just realized you need to go smaller than the original. The above would work if the new overflow is larger than the starting state...
In this specific case, you might want to avoid the transform all together and instead scale the background image. Then scale the element using your JS function. In this case, the background will scale to fit its container.
.child {
background-image: url("https://i.redd.it/7ifkx5z39b631.jpg");
background-size: contain;
width: calc(4900px * 0.25);
height: calc(7000px * 0.25)
}

Bootstrap 3 align elements into circle

I have a question about forming elements to form a circle, or align elements to form a circle, depending how you like it to be pronounce, now back to question:
There are couple of examples here on stackoverflow and on the internet regarding this question but any off these examples do not cover Bootstrap 3 responsive align elements to form a circle, I would like if someone can make an example out of mine working JSFiddle example (text needs to be a center of the circle, because I need to animate it), and make this using bootstrap grid system.
Is this possible, can you please explain to me how you do this so I can learn something out of this.
TL;DR; http://jsfiddle.net/k7yxtpc7/
Edit with (very long?) explanation:
So we start off with a bootstrap's hierarchy:
<div class="container-fluid">
<div class="row">
<div class="circle_container col-md-6 col-md-offset-3 col-sm-8 col-sm-offset-2 col-xs-12">
</div>
</div>
</div>
The planetary of images will be put inside .circle_container. Our aim is to make sure the whole circle will respond to .circle_container's width changes and adapt correctly. This way any change Boostrap makes to the container will be reflected on the circle itself, making it Bootstrap-compliant.
First we have to prepare .circle_container a bit. Since it's a whole circle the container must be square-ish. We must find a way to make .circle_container's height to be always equal to its width. I do this by putting a square img inside .circle_container, then scale the img's size according to the container's width:
<div class="circle_container ...">
<img class="transparent_square" src="http://i.stack.imgur.com/5Y4F4.jpg" width="2" height="2" />
</div>
.transparent_square{
width: 100%;
height: auto;
}
Note: I couldn't find a transparent square image on the web, so I had to make do with a white square. In your product a 2pxx2px transparent image is best.
Great, now we have a square container. But we've put a limiter on ourselves too. From now on, the img must be the only child of .circle_container that have a static (default) or relative position, because any further child will extend the container, destroying the square shape. Not a big deal though, since we'll position other children absolute anyway.
Next up is the central text bubble:
<div class="central_text text-center">
<h3>Special for you</h3>
<h5>Lorem ipsum</h5>
</div>
.central_text{
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
position: absolute;
}
The translate trick make use of the fact that percentile value in css transform use the element's pre-render width & height, while all other positioning rule use its parent's width & height instead. By giving the element left: 50%; top: 50% we put its top left corner at the center of its parent, then we translate it up and to the left by 50% of its own width and height, effectively centering the element within its parent. This is only 1 of several methods to center an element within a container, but it fits our situation best because the element is absolutely positioned.
Finally we reach the part where we create the circle. To sum up the trick here: we put the actual image inside a container, which has a pivot point at the center of the container, and position the image off to 1 side of the container equal to the radius of the circle. This way when we rotate the image's container, the image will be moved in a circle around the center of the container, like a drawing compass. After the image has reached our desired position, we rotate the image itself by the same degree in the other direction to compensate for the tilt in orientation, making the image upright again.
The container and image:
<div class="moon_container moon1"><img class="moon moon1" src="http://letscode.ghost.io/content/images/2015/09/stackoverflow.png"></div>
.moon_container{
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
width: 20%; /* This is the final width of the image */
}
I set the width for .moon_container as 20% of .circle_container's width. This will be the width of the images in our final circle. Increasing or decreasing this number simply change the size of the image to your desire.
Now to offset the image from its container:
.moon{
width: 100%;
height: auto;
/* The image can be relative positioned without breaking anything because its parent is absolute */
position: relative;
/* The radius of the circle. This is equal to 175%*20% = 35% of .circle_container's width */
left: 175%;
}
Note that CSS's left use an element's direct parent's width as base unit. If you changed .moon_container's width in the previous part, the actual distance of the images will change as well.
Finally, rotations (I use moon2 as the example here because moon1 doesn't need to rotate):
/* Container rotate 45deg clockwise... */
.moon_container.moon2{
/* 360/8 (the number of images) = 45deg */
transform: translate(-50%, -50%) rotate(45deg);
}
/* ... while the image rotate 45deg counter-clockwise */
.moon.moon2{
transform: rotate(-45deg);
}
Why transform: translate(-50%, -50%) rotate(45deg); and not transform: rotate(45deg);? Because we declared transform: translate(-50%, -50%); earlier for the .moon_container (the centering trick). If we only write transform: rotate(45deg); here, the CSS parser will override the previous rule with the new one, losing the translate part. So we have to append manually.
Repeat the process to all 8 images and we're done!
If you have undetermined number of images, simply use javascript to calculate this rotation part for each image.
I hope my explanation was useful for you. I've always been bad at explanation...
Edit 2: http://jsfiddle.net/k7yxtpc7/3/ Text change on hover version as per OP's request. There's only 1 thing to note in this part, that is
$("body").on({
mouseenter : function(event){
...
},
mouseleave : function(event){
...
}
}, ".moon");
It is good habit to bind all events on either 'body' or document, instead of binding them on the actual elements itself (the .moon). This way you:
Always use only 1 event listener for the hover event, instead of 8 (you can imagine how the number scale up on an actual product).
When you add more images later, you don't have to bind the event on the new .moon again.
Original Answer:
As the requirement is rather vague, I couldn't know if my solution would satisfy you. My solution is based on 3 assumptions:
The entire planetary of images are only based on view port width, similar to how Bootstrap handle its responsive design. If you want to take view port height into consideration maybe I can conjure up another version.
The images are scaled based on the Bootstrap container's width, in order to make sure there's enough space to display all images.
Typography uses Bootstrap's defaults.
The solution avoid using javascript at the cost of not being able to add/remove images on-the-fly. If a dynamic number of images is your intention, I will put calculations in.
Sexy animations compatible.
Unfortunately Bootstrap's center-block only center a block horizontally, I had to make use of the translate trick to center the pivot point.
.central_text{
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
position: absolute;
}
This is only an answer placeholder. I will write detailed explanation once we have a satisfactory solution.

How to make a CSS element extend beyond all borders of containing div?

I have a JS Fiddle going of something that I am trying to do here. As you can see I have a circle sitting in the center of a div. When you run the script it expends evenly in all directions until it hits the left and top of the screen. What I want to happen is the circle to expand evenly in all directions (through all of the containing divs borders) so that it fills the screen with red, but I am at a loss on how to get it to overflow left and top.
here is the fiddle:
http://jsfiddle.net/dkarasinski/UxtJV/711/
HTML
<div class="outerwrapper">
<div class="test">
<div class="circle"></div>
</div>
</div>
jquery
$(document).ready(function() {
setTimeout(function() {
$('.circle').addClass('open');
}, 2000);
});
Any help would be appreciated!
I think it's more to do with your top and left absolute on the .open css class style.
Here's a fork of your fiddle with -200px on both top and left: http://jsfiddle.net/ghopkins/3eybkrz1/
Change in code:
div.open {
top: -200px;
left: -200px;
width: 1000px;
height: 1000px;
}
Your version is pinning the top left 'corner' of the circle and expanding down and right.
You're explicitly putting the <div> at (0, 0) on the page.
Instead of trying to figure out the position, you can just take advantage of the transform property:
div.open {
transform: scale(50, 50);
}
That makes the circle 50 times bigger in both the X and Y axes. The element won't change position; it'll just get bigger.
you can use this
transform: translate(-25%, -25%);
demo - http://jsfiddle.net/UxtJV/714/

css/ jQuery - center absolute positioned div

The div is 50% opaque and is displayed on top of the site's content, and it has a fixed width of 960 pixels (it's created by jQuery).
How can I center it horizontally?
margin: 0 auto; doesn't work :(
margin: 0 auto; won't work for elements that are absolutely positioned. Instead, we can work with the properties of the element itself. Check out the fiddle...
http://jsfiddle.net/UnsungHero97/HnzyT/2/
To center it horizontally is easy since you know the width AND its positioned absolutely. All you have to do is give it 2 CSS properties:
width: 960px;
position: absolute;
/* ... other CSS properties... */
left: 50%; /* 1. move it to the right 50% of the width of the page; now the left side of the element is exactly in the middle */
margin-left: -480px; /* move the element to the left exactly half of its width and now the center of the element is centered horizontally */
If you want to center it both vertically and horizontally, you need to know how wide AND how tall the element is.
I hope this helps.
Hristo
Just subtract the window midpoint from half the width of you element on resize. Here's a simple plugin that you could easily accomodate to center vertically if need be as well:
$.fn.centerMe = function () {
this.css('left', $(window).width()/2 - $(this).width()/2);
};
$(window).resize(function() { $('#yourElem').centerMe(); });
$('#yourElem').centerMe();
See working example →

Categories

Resources