I'm trying to achieve this effect with jQuery.
I wrote some of the code, but it's buggy (move to the bottom-right corder and you'll see).
check it out
Basically, if there's an already-built jQuery plugin that you know of that does this, I'd be very happy using it, if not, any help with my formula would be appreciated. This is what I get for not paying attention in Maths classes :)
Thanks in advance.
Maikel
Overall I think this is what you're looking for:
$.fn.sexyImageHover = function() {
var p = this, // parent
i = this.children('img'); // image
i.load(function(){
// get image and parent width/height info
var pw = p.width(),
ph = p.height(),
w = i.width(),
h = i.height();
// check if the image is actually larger than the parent
if (w > pw || h > ph) {
var w_offset = w - pw,
h_offset = h - ph;
// center the image in the view by default
i.css({ 'margin-top':(h_offset / 2) * -1, 'margin-left':(w_offset / 2) * -1 });
p.mousemove(function(e){
var new_x = 0 - w_offset * e.offsetX / w,
new_y = 0 - h_offset * e.offsetY / h;
i.css({ 'margin-top':new_y, 'margin-left':new_x });
});
}
});
}
You can test it here.
Notable changes:
new_x and new_y should be divided by the images height/width, not the container's height/width, which is wider.
this is already a jQuery object in a $.fn.plugin function, no need to wrap it.
i and p were also jQuery objects, no need to keep wrapping them
no need to bind mousemove on mouseenter (which rebinds) the mousemove will only occur when you're inside anyway.
Nick Craver beat me to an answer by about 10 minutes, but this is my code for this, using background-image to position the image instead of an actual image.
var img = $('#outer'),
imgWidth = 1600,
imgHeight = 1200,
eleWidth = img.width(),
eleHeight = img.height(),
offsetX = img.offset().left,
offsetY = img.offset().top,
moveRatioX = imgWidth / eleWidth - 1,
moveRatioY = imgHeight / eleHeight - 1;
img.mousemove(function(e){
var x = imgWidth - ((e.pageX - offsetX) * moveRatioX),
y = imgHeight - ((e.pageY - offsetY) * moveRatioY);
this.style.backgroundPosition = x + 'px ' + y + 'px';
});
The huge amount of variables are there because the mousemove event handler has to be as efficient as possible. It's slightly more restrictive, because you need to know the dimensions, but I think the code can be easily altered to work with imgs for which the size can be calculated easily.
A simple demo of this: http://www.jsfiddle.net/yijiang/fq2te/1/
Related
I am trying to implement a image maginfier on hover.I tried to replicate the code as in w3schools which is purely of Javascript.I am trying to implement the following code in Angular
https://www.w3schools.com/howto/tryit.asp?filename=tryhow_js_image_magnifier_glass
I used the above method in typescript and called it from ngOnInit in Angular but i am not able to get any result from the method.I have ensured the id is passed correctly and validated the method is being called .But still not able to get any result .I wish not to use any npm packages for magnifier since most of them had bugs.
component.ts
ngOnInit(){
this.magnify(imgID, zoom)
}
magnify(imgID, zoom) {
var img, glass, w, h, bw;
img = document.getElementById(imgID);
/*create magnifier glass:*/
glass = document.createElement("DIV");
glass.setAttribute("class", "img-magnifier-glass");
/*insert magnifier glass:*/
img.parentElement.insertBefore(glass, img);
/*set background properties for the magnifier glass:*/
glass.style.backgroundImage = "url('" + img.src + "')";
glass.style.backgroundRepeat = "no-repeat";
glass.style.backgroundSize = (img.width * zoom) + "px " + (img.height * zoom) + "px";
bw = 3;
w = glass.offsetWidth / 2;
h = glass.offsetHeight / 2;
/*execute a function when someone moves the magnifier glass over the image:*/
glass.addEventListener("mousemove", moveMagnifier);
img.addEventListener("mousemove", moveMagnifier);
/*and also for touch screens:*/
glass.addEventListener("touchmove", moveMagnifier);
img.addEventListener("touchmove", moveMagnifier);
function moveMagnifier(e) {
var pos, x, y;
/*prevent any other actions that may occur when moving over the image*/
e.preventDefault();
/*get the cursor's x and y positions:*/
pos = getCursorPos(e);
x = pos.x;
y = pos.y;
/*prevent the magnifier glass from being positioned outside the image:*/
if (x > img.width - (w / zoom)) {x = img.width - (w / zoom);}
if (x < w / zoom) {x = w / zoom;}
if (y > img.height - (h / zoom)) {y = img.height - (h / zoom);}
if (y < h / zoom) {y = h / zoom;}
/*set the position of the magnifier glass:*/
glass.style.left = (x - w) + "px";
glass.style.top = (y - h) + "px";
/*display what the magnifier glass "sees":*/
glass.style.backgroundPosition = "-" + ((x * zoom) - w + bw) + "px -" + ((y * zoom) - h + bw) + "px";
}
function getCursorPos(e) {
var a, x = 0, y = 0;
e = e || window.event;
/*get the x and y positions of the image:*/
a = img.getBoundingClientRect();
/*calculate the cursor's x and y coordinates, relative to the image:*/
x = e.pageX - a.left;
y = e.pageY - a.top;
/*consider any page scrolling:*/
x = x - window.pageXOffset;
y = y - window.pageYOffset;
return {x : x, y : y};
}
}
Here is a working stackblitz as per your requirements. It shows the implementation of image zoom functionality mentioned on w3school.
https://stackblitz.com/edit/angular-w3school-image-magnification
You have not shown your html and css files. So, I am not totally sure but the following might be the reason why zoom is not working for you.
Problem is that img-magnifier-glass div element is created using classical DOM method 'document.createElement'. And then, class 'img-magnifier-glass' is applied to it, again using a classical DOM method (setAttribute). But, in angular, styles are encapsulated. So, if you have added a class definition of '.img-magnifier-glass' in app.component.css then that class won't be applied to glass div since it is not mentioned in the template (app.component.html). See this for more info - https://github.com/angular/angular/issues/7845
To fix this, you can either move definition of class '.img-magnifier-glass' to styles.css (Where global styles are defined)
or you can keep the class in app.component.css but use pseudo-selector ::ng-deep with it. Applying the ::ng-deep pseudo-class to any CSS rule completely disables view-encapsulation for that rule. Any style with ::ng-deep applied becomes a global style.
::ng-deep .img-magnifier-glass {
}
or you can stop style encapsulation for component by specifying
#Component({
// ...
encapsulation: ViewEncapsulation.None, //<<<<< this one!
styles: [
// ...
]
})
It will be better will be if you use Renderer2 (https://angular.io/api/core/Renderer2) instead for creating dynamic elements like glass element here. Renderer2 will take care of correctly encapsulating class applied on elements created using it.
I ran into the same issue but for image zoomer which has the same implementation of magnifier. I got it working by tweaking the css and ts code (which was taken from the magnifier and combined with the zoomer). the answer above is not what I am looking for coz I need the zoomed img to be in a different box and not on top of the img itself. Here is the stackblitz code which I modified to suit what I need.
For implementing image magnification feature like W3School and Amazon in Angular, you can use npm package ng-img-magnifier.
Here is the working DEMO.
<ng-img-magnifier
[thumbImage]='img' [fullImage]='img2'
[top]='top' [right]='right'
[lensWidth]='lensewidth' [lensHeight]='lensheight'
[imgWidth]='imgWidth' [imgHeight]='imgheight'
[resultWidth]='resultWidth' [resultHeight]='resultheight'
>
</ng-img-magnifier>
This package comes with full customization options.
Hopefully this will resolve your issue.
I am trying to make something where a bunch of circles (divs with border-radius) can be dynamically generated and laid out in their container without overlapping.
Here is my progress so far - https://jsbin.com/domogivuse/2/edit?html,css,js,output
var sizes = [200, 120, 500, 80, 145];
var max = sizes.reduce(function(a, b) {
return Math.max(a, b);
});
var min = sizes.reduce(function(a, b) {
return Math.min(a, b);
});
var percentages = sizes.map(function(x) {
return ((x - min) * 100) / (max - min);
});
percentages.sort(function(a, b) {
return b-a;
})
var container = document.getElementById('container');
var width = container.clientWidth;
var height = container.clientHeight;
var area = width * height;
var maxCircleArea = (area / sizes.length);
var pi = Math.PI;
var maxRadius = Math.sqrt(maxCircleArea / pi);
var minRadius = maxRadius * 0.50;
var range = maxRadius - minRadius;
var radii = percentages.map(function(x) {
return ((x / 100) * range) + minRadius;
});
function getRandomArbitrary(min, max) {
return Math.random() * (max - min) + min;
}
var coords = [];
radii.forEach(function(e, i) {
var circle = document.createElement('div');
var randomTop = getRandomArbitrary(0, height);
var randomLeft = getRandomArbitrary(0, width);
var top = randomTop + (e * 2) < height ?
randomTop :
randomTop - (e * 2) >= 0 ?
randomTop - (e * 2) :
randomTop - e;
var left = randomLeft + (e * 2) < width ?
randomLeft :
randomLeft - (e * 2) >= 0 ?
randomLeft - (e * 2) :
randomLeft - e;
var x = left + e;
var y = top + e;
coords.push({x: x, y: y, radius: e});
circle.className = 'bubble';
circle.style.width = e * 2 + 'px';
circle.style.height = e * 2 + 'px';
circle.style.top = top + 'px';
circle.style.left = left + 'px';
circle.innerText = i
container.appendChild(circle);
});
I have got them being added to the parent container but as you can see they overlap and I don't really know how to solve this. I tried implementing a formula like (x1 - x2)^2 + (y1 - y2)^2 < (radius1 + radius2)^2 but I have no idea about this.
Any help appreciated.
What you're trying to do is called "Packing" and is actually a pretty hard problem. There are a couple potential approaches you can take here.
First, you can randomly distribute them (like you are currently doing), but including a "retry" test, in which if a circle overlaps another, you try a new location. Since it's possible to end up in an impossible situation, you would also want a retry limit at which point it gives up, goes back to the beginning, and tries randomly placing them again. This method is relatively easy, but has the down-side that you can't pack them very densely, because the chances of overlap become very very high. If maybe 1/3 of the total area is covered by circle, this could work.
Second, you can adjust the position of previously placed circles as you add more. This is more equivalent to how this would be accomplished physically -- as you add more you start having to shove the nearby ones out of the way in order to fit the new one. This will require not just finding the things that your current circle hits, but also the ones that would be hit if that one was to move. I would suggest something akin to a "springy" algorithm, where you randomly place all the circles (without thinking about if they fit), and then have a loop where you calculate overlap, and then exert a force on each circle based on that overlap (They push each other apart). This will push the circles away from each other until they stop overlapping. It will also support one circle pushing a second one into a third, and so on. This will be more complex to write, but will support much more dense configurations (since they can end up touching in the end). You still probably need a "this is impossible" check though, to keep it from getting stuck and looping forever.
I'm writing a little script that allows the user to move and resize a div. I need to keep the aspect ratio and my logic doesn't work.
function resizing() {
var currentHeight = elmnt.offsetHeight;
var currentWidth = elmnt.offsetWidth;
var newHeight = currentHeight + (event.pageY - currentY);
var newWidth = currentWidth + (event.pageX - currentX);
var ratio = currentWidth / currentHeight;
if(ratio < 1) {
newwidth = parseInt(newHeight * ratio);
}
else {
newheight = parseInt(newWidth / ratio);
}
elmnt.style.height = newHeight + "px";
elmnt.style.width = newWidth + "px";
currentY = event.pageY;
currentX = event.pageX;
}
The script kind of works. But unfortunately it doesn't keep the aspect ratio completely correct. Sometimes, when I resize horizontyl only, the old height remains the same, sometimes it works, but one length gets resized with a little offset.
When I resize up and down and up and down again, the lengths gets more and more equal and when it is a proper square, everything is right.
Hwo can I fix my problems? Where is my fallacy?!
Your ratio is wrong I think.
You need to calculate this by taking the old width and dividing by the new width, or old height / new height.
e.g.
var ratio = newWidth / currentWidth;
newHeight = currentHeight * ratio;
Change it about if it is the height that is changing.
I could fiy it.
THANK YOU VERY MUCH!
My problem was that I first, had to track of which axis has more change. The second problem, which I didn't recognized was, that I had BIG problems with rounding issues.
When setting the css size using jQuery, it rounds. And I took the height for ratio calculations every single event.
That means that the inaccuracy was getting more and more bad.
Now I took this into account and figured out a way to get this working very good.
I now do this directly onclick and just update them instead of getting from the element:
currentHeight = $("#dragger").height();
currentWidth = $("#dragger").width();
So thanks again for your help! Here is my final result:
http://jsfiddle.net/julian_weinert/xUAZ5/30/
You have to do this, get the min scale (ratio). The code below is a part of my PHP script, but easily translated to JS. $iSrc = Source and $iDest is destination MAX width/height.
Your problem is you don't get the right ratio. The first line to define the ratio is where your problem will be solved. It gets the lowest ratio of the width or height. You just do width/height and forget height/width. That's why vertical scaling is not correct.
$scale = min($iDestWidth/$iSrcWidth, $iDestHeight/$iSrcHeight);
if($scale >= 1){
$iDestHeight = $iSrcHeight;
$iDestWidth = $iSrcWidth;
}else{
$iDestWidth = floor($scale*$iSrcWidth);
$iDestHeight = floor($scale*$iSrcHeight);
}
replace your if(ratio < 1) block with the following. offsetx and offsety relate to your (event.pageX - currentX) and (event.pageY - currentY):
if (Math.abs(offsetx) > Math.abs(offsety)) {
ratio = currentHeight/currentWidth;
newHeight = currentHeight + (offsetx * ratio);
newWidth = currentWidth + offsetx;
} else {
ratio = currentWidth/currentHeight;
newHeight = currentHeight + offsety;
newWidth = currentWidth + (offsety * ratio);
}
here is a quick jsfiddle of the whole thing in action: http://jsfiddle.net/8TWRV/
I am in need of some math help. I am trying to dynamically transform my Raphael set of elements to a given bound box within my canvas.
For example, say my canvas (paper) is 600 x 300 and is filled with paths. These paths are all in a set.
Now I want fill my canvas with a given bound box. The bound box is in pixel coordinates. e.g. [[50,10], [100,20]]
So the end result would be a function call that would zoom and position the SVG elements. This would cause the canvas to be cropped to the coordinate bounds.
var bbox = [[50,10], [100,20]]
animateToBoundBox(set, bbox, duration);
function animateToBoundBox(set, bbox, duration) { /* beautiful code */ }
I think the way to accomplish this would be by using the element matrix but I'm not sure. What do you think the most elegant way of handling this would be?
Thanks
The other answers are correct -- you want to use setViewBox.
Here's a version that supports animation. It's not entirely beautiful and you'll have to look at the page source to extract the code, but it should do more or less exactly what you want.
Here's the view box animation as a Raphael extension:
Raphael.fn.animateViewBox = function animateViewBox( x, y, w, h, duration, easing_function, callback )
{
var cx = this._viewBox ? this._viewBox[0] : 0,
dx = x - cx,
cy = this._viewBox ? this._viewBox[1] : 0,
dy = y - cy,
cw = this._viewBox ? this._viewBox[2] : this.width,
dw = w - cw,
ch = this._viewBox ? this._viewBox[3] : this.height,
dh = h - ch,
self = this;;
easing_function = easing_function || "linear";
var interval = 25;
var steps = duration / interval;
var current_step = 0;
var easing_formula = Raphael.easing_formulas[easing_function];
var intervalID = setInterval( function()
{
var ratio = current_step / steps;
self.setViewBox( cx + dx * easing_formula( ratio ),
cy + dy * easing_formula( ratio ),
cw + dw * easing_formula( ratio ),
ch + dh * easing_formula( ratio ), false );
if ( current_step++ >= steps )
{
clearInterval( intervalID );
callback && callback();
}
}, interval );
}
And the (not so beautiful) demonstration is here: http://voidblossom.com/tests/easedViewBox.php
If you're really bent on using transform (which could have a few benefits if leveraged well, but will in general be fragile compared to viewbox manipulation), there's another example using transform located at http://voidblossom.com/tests/zoomByTransform.php.
Not sure if I completely understand what you are looking for, but it sounds like you want to zoom the view to a specific bounding box. Have you looked at the setViewBox function? Basically your function would call it like this:
setViewBox(bbox[0][0], bbox[0][1], bbox[1][0] - bbox[0][1], bbox[1][1] - bbox[0][0])
From what I can tell, everything you want to accomplish would be better handled with Paper.setViewBox() in an animation. See http://raphaeljs.com/reference.html#Paper.setViewBox
I have a number of Raphael / SVG items that could possibly go outside the boundary. What I want is to be able to auto zoom and center the SVG to show all contents.
I have some partially working code that centers it appropriately, I just cannot figure out how to get the scaling working
Edit
This now works... but doesnt center align, and requires padding...
var maxValues = { x: 0, y: 0 };
var minValues = { x: 0, y: 0 };
//Find max and min points
paper.forEach(function (el) {
var bbox = el.getBBox();
if (bbox.y < minValues.y) minValues.y = bbox.y;
if (bbox.y2 < minValues.y) minValues.y = bbox.y2;
if (bbox.y > maxValues.y) maxValues.y = bbox.y;
if (bbox.y2 > maxValues.y) maxValues.y = bbox.y2;
if (bbox.x < minValues.x) minValues.x = bbox.x;
if (bbox.x2 < minValues.x) minValues.x = bbox.x2;
if (bbox.x > maxValues.x) maxValues.x = bbox.x;
if (bbox.x2 > maxValues.x) maxValues.x = bbox.x2;
});
var w = maxValues.x - minValues.x;
var h = maxValues.y - minValues.y;
console.log(minValues,maxValues,w,h)
paper.setViewBox(minValues.x, minValues.y, w, h, false);
I'm using this snippet of code to center the viewbox that contains all of the SVG that I want to show in almost Full Screen.
var elmnt = $(viewport);
var wdif = screen.width - width;
var hdif = screen.height - height;
if (wdif < hdif){
var scale = (screen.width - 50) / width;
var ty = (screen.height - (height * scale)) / 2
var tx = 20;
}else{
var scale = (screen.height - 50) / height;
var tx = (screen.width - (width * scale)) / 2
var ty = 20;
}
elmnt.setAttribute("transform", "scale("+scale+") translate("+tx+","+ty+")");
What it does is to use the difference between the viewport size and the screen size, and use it as the scale. Off course yo need to have all the elements wrapped in a viewbox. I hope this works for you to. Bye!
EDIT
I´ve made this fiddle.... http://jsfiddle.net/MakKZ/
While in the original snippet I´ve used the screen size, on the fiddle, you are going to see I´m using the size of the HTML element that jsfiddle uses. No matter how many circles (or the size of the circles) you draw on the screen you always see them all.