Keep image centered after updating x with mouse position - javascript

I have a script that moves an image slightly to the left or right when the user moves their mouse. The problem is this image is always in the top left of my window when I need it to always stay in the center.
<html>
<head>
</head>
<body>
<img id="logo" src="logoHeader.png" style="position:absolute;" />
</body>
<script lang="javascript">
function updateLogoPosition( e )
{
var logo = document.getElementById("logo");
var m = e.x / 12;
logo.style.left = m + "px";
}
document.onmousemove = updateLogoPosition;
</script>
</html>

You would have to do some more calculation to do this.
You need to know the width and height of the viewport to find the middle. Then you need to normalise the mouse position so that you calculate the offset from the centre line not from the top left as you e.x was doing.
Something like this should do it, where "modifier" will allow you to change the violence of the offset.
<html>
<head>
</head>
<body>
<img id="logo" src="http://placehold.it/150x150" style="position:absolute;" />
<script>
window.onload = setInitialLogoPosition;
document.onmousemove = updateLogoPosition;
function setInitialLogoPosition(){
var bodyHeight = document.body.clientHeight;
var bodyWidth = document.body.clientWidth;
var logo = document.getElementById("logo");
var logoWidth = logo.width;
var logoHeight = logo.height;
var leftOffset = (bodyWidth/2 - logoWidth/2);
var topOffset = (bodyHeight/2 - logoHeight/2);
logo.style.left = leftOffset;
logo.style.top = topOffset;
}
function updateLogoPosition( e ){
// Get height and width of body
var bodyHeight = document.body.clientHeight;
var bodyWidth = document.body.clientWidth;
// Get height and width of logo
var logo = document.getElementById("logo");
var logoWidth = logo.width;
var logoHeight = logo.height;
/* Normalise the mouse so that 0 is the centre
with negative values to the left and positive to the right */
var x = (e.x / bodyWidth * 100) - 50;
var y = (e.y / bodyHeight * 100) - 50;
// Calculate the position of the logo without mouse manipulation
var leftOffset = (bodyWidth/2 - logoWidth/2);
var topOffset = (bodyHeight/2 - logoHeight/2);
// Set violence of offset
var modifier = 0.5;
// Add the mouse offset to the central position
leftOffset += (x * modifier);
topOffset += (y * modifier);
// Apply the calculated position to the logo
logo.style.left = leftOffset + "px";
logo.style.top = topOffset + "px";
}
</script>
</body>
</html>

To center horizontally you can do it with CSS:
<img id="logo" src="logoHeader.png" style="position:relative; text-algin:center; display: block; margin: 0 auto;" />
jsFiddle

Related

Center image around user clicked position

I am trying to move an image so that it is centered around the position that the user clicked, both vertically and horizontally, using JavaScript. How would this be accomplished?
I have tried the following code, but it aligns the top left corner of the image to the position that was clicked, which is not what I want.
document.onclick = userClicked;
function userClicked() {
var x = event.clientX;
var y = event.clientY;
var cat = document.getElementById("catAppear");
cat.style.display = '';
cat.style.position = 'absolute';
cat.style.left = x + 'px';
cat.style.top = y + 'px';
}
<div class="container">
<img alt="catAppear" id="catAppear" style="display: none" src="https://www.coopmcs.com/dotclear/public/chat.png" />
</div>
Simply subtract half the image's width from the x-coordinate and half the height from the y-coordinate to center the image around the clicked position.
document.onclick = userClicked;
function userClicked() {
var x = event.clientX;
var y = event.clientY;
var cat = document.getElementById("catAppear");
cat.style.display = '';
cat.style.position = 'absolute';
cat.style.left = x - cat.width / 2 + 'px';
cat.style.top = y - cat.height / 2 + 'px';
}
<div class="container">
<img alt="catAppear" id="catAppear" style="display: none" src="https://www.coopmcs.com/dotclear/public/chat.png"/>
</div>
You can take the width and height of the image and divide them by two, then subtract the x by the width divided by two and subtract the y by the height divided by two. This'll give you the center of the image.
document.onclick = userClicked;
function userClicked() {
var x = event.clientX;
var y = event.clientY;
var cat = document.getElementById("catAppear");
cat.style.display = "block";
cat.style.left = x - (cat.width/2) + 'px';
cat.style.top = y - (cat.height/2) + 'px';
};
#catAppear {
position: absolute;
}
<div class="container">
<img alt="catAppear" id="catAppear" style="display: none" src="https://www.coopmcs.com/dotclear/public/chat.png" />
</div>

position (X, Y coordinates) update on page resize

Trying to capture the position of click on an image (marked as x for end users). But on window resize the 'X' position changes. Is something I am missing in my code, how can i maintain the position in portrait and landscape modes
<script>
$("#_img").on("click",function(event){
var X = event.pageX-5, Y = event.pageY-5;
$("#marker").css({
"left":X,
"right":Y
}).show();
});
</script>
<img id="_img" src="car.png" width="550px" height="168px"/>
<div id="_mrk" style="display:none;">x</div>
You have to update position of 'x' everytime window resized or orientation changed and image should be in perentage instead of pixels
var width = 0;
var height = 0;
$("#_img").on("click", function(event) {
var X = event.pageX,
Y = event.pageY;
$("#_mrk").css({
"left": X,
"top": Y
}).show();
width = $("#_img").width();
height = $("#_img").height();
});
function getNewValue(posValue, oldImgPos, newImgPos) {
return posValue * (newImgPos / oldImgPos);
}
$(window).resize(function() {
var newx = getNewValue($('#_mrk').offset().left, width, $("#_img").width());
$("#_mrk").css("left", newx);
var newy = getNewValue($('#_mrk').offset().top, height, $("#_img").height());
$("#_mrk").css("top", newy);
width = $("#_img").width();
height = $("#_img").height();
});
#_mrk {
position: absolute;
}
#_img {
width: 100%;
}
<img id="_img" src="http://clipartion.com/wp-content/uploads/2015/11/colorable-car-line-art-free-clip-art.png" width="550px" height="168px" />
<div id="_mrk" style="display:none;">x</div>
Save value of document width when img is clicked. Add event listener to resize event and change X and Y values when it fired:
var X, Y, doc_width, a_ratio;
$("#_img").on("click", function(event){
X = event.pageX-5;
Y = event.pageY-5;
doc_width = document.documentElement.clientWidth;
a_ratio = $(this).width()/$(this).height();
move_mark(X, Y);
});
$(window).on("resize", function(){
var x = X + (document.documentElement.clientWidth - doc_width);
var y = Y + (x - X)/a_ratio;
move_mark(x, y);
})
function move_mark(X,Y){
$("#marker").css({
"left":X,
"right":Y
}).show();
}
You can use percentage instead of pixels to support all sizes.
First of all make sure the container of the img and the marker is position relative, and the marker is position absolute.
Then, when clicking you will need to calculate the X and Y within the image, and then based on that calculate percentage.
var img = $("#_img");
img.on("click", function(event){
var x = event.pageX - this.offsetLeft;
var y = event.pageY - this.offsetTop;
var left = 'calc(' + ((x / img.width()) * 100) + '% - 5px)';
var right = 'calc(' + ((y / img.height()) * 100) + '% - 5px)';
$("#marker").css({
"left": left,
"right": right
}).show();
});

How do I find the center of an image, and place another image on top of it?

HTML:
<img src="img/image1.jpg" id = "image1" style="width: 100%;" allign = "center">
JavaScript:
var image1 = document.getElementById("image1");
How would I get the center of this given image, and then place another image which has an absolute position on top of it dead center?
You can use getBoundingClientRect() on the images to find their exact position and calculate using those values. This method will take into consideration the CSS size as well as scroll position etc.
The second image is placed below using fixed position, for demo, but you can use a parent div set to relative and place the image inside that using absolute etc.
Example
function centerImages() {
var image1 = document.getElementById("image1");
var rect1 = image1.getBoundingClientRect();
var cx = rect1.left + rect1.width * 0.5; // find center of first image
var cy = rect1.top + rect1.height * 0.5;
var image2 = document.getElementById("image2");
var rect2 = image2.getBoundingClientRect();
var x = cx - rect2.width * 0.5; // use center of first, subtract second
var y = cy - rect2.height * 0.5;
image2.style.cssText = "position:fixed;left:" + x + "px; top:" + y + "px";
}
window.onload = window.onresize = window.onscroll = centerImages;
<img src="http://i.stack.imgur.com/UDTPI.gif" id="image1" style="width: 100%;">
<img src="http://i.stack.imgur.com/fk5Js.gif" id="image2">
http://jsfiddle.net/33ra14az/1/ here's a way I came up with using JS + resize event for responsive.
function setImg() {
var img1 = document.getElementById('image1'),
img2 = document.getElementById('image2'),
offtop = ((img1.offsetHeight/2)-(img2.offsetHeight/2)),
offleft = ((img1.offsetWidth/2)-(img2.offsetWidth/2));
img2.style.top = offtop + "px";
img2.style.left = offleft + "px";
}
window.load = setImg();
window.addEventListener('resize',setImg);
well you can try this :
$(document).ready(function() {
var top=($("#image1").height()/2)-($("#image2").height()/2);
var left=($("#image1").width()/2)-($("#image2").width()/2);
$("#image2").css('left',left+'px');
$("#image2").css('top',top+'px');
});
and the css is simple:
#image2{
position: absolute;
display:block;
width:100px;
height:100px;
}
and this is the html code:
<img src="http://doc.jsfiddle.net/_downloads/jsfiddle-logo.png" id = "image1" style="width: 100%;" allign = "center">
<img src="http://www.hakandemirel.com.tr/blog/wp-content/uploads/jsfiddle.png" id ="image2">
this is demo:
http://jsfiddle.net/yysdged6/22/

resizable and draggable div with fixed surface area

Is it possible to make a resizable and draggable div with a fixed surface area?
Example: I have a square div with a surface area of 10000px² (100 x 100px) and then I change the width (with the mouse on the corner or on the edge) to 50px, the heigth should now change automaticly to 200px so the surface area stays 10000px².
Then I´d like to drag it all over the page, resize it again etc...
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery UI Draggable - Default functionality</title>
<link rel="stylesheet"
href="http://code.jquery.com/ui/1.10.4/themes/smoothness/jquery-
ui.css">
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script src="http://code.jquery.com/ui/1.10.4/jquery-
ui.js"></script>
<link rel="stylesheet" href="/resources/demos/style.css">
<style>
#draggable { width: 100px; height: 100px; padding: 0.5em; border:
1px solid;}
</style>
<script>
$(function() {
$( "#draggable" ).draggable().resizable();
});
</script>
</head>
<body>
<div id="draggable" class="ui-widget-content">
<p>Drag me around</p>
</div>
</body>
</html>
ok, so here is the code, I have resizable and draggable div but now I need the fixed surface area (eg 10000px²) as I mentioned before...
you can use jquery's UI to do all of this.
use http://jqueryui.com/draggable/ to allow for dragging,
use http://jqueryui.com/resizable/ to allow for resizing
using the resize event, you can have jquery modify the div so it will follow any height/width rules you want.
Try this:
(function(draggable) {
var elm = document.getElementById(draggable);
elm.onmousedown = drag;
function stop() {
document.onmouseup = null;
document.onmousemove = null;
}
function drag(e) {
if (e.target == elm) {
var absX = e.clientX;
var absY = e.clientY;
var left = parseInt(getComputedStyle(elm).left, 10);
var top = parseInt(getComputedStyle(elm).top, 10);
var relX = absX - left;
var relY = absY - top;
document.onmouseup = stop;
document.onmousemove = function(e) {
var absX = e.clientX;
var absY = e.clientY;
elm.style.left = absX - relX + "px";
elm.style.top = absY - relY + "px";
}
}
}
})("box");
(function(resizeable) {
var elm = document.getElementById(resizeable);
var wHandler = elm.childNodes[1];
var hHandler = elm.childNodes[3];
wHandler.onmousedown = resizeW;
hHandler.onmousedown = resizeH;
function stop() {
elm.style.cursor = "";
document.body.style.cursor = "";
document.onmouseup = null;
document.onmousemove = null;
}
var w = 100;
var h = 100;
var area = w * h;
function resizeW(e) {
elm.style.cursor = "w-resize";
document.body.style.cursor = "w-resize";
var left = parseInt(window.getComputedStyle(elm, null)["left"], 10);
document.onmouseup = stop;
document.onmousemove = function(e) {
var absX = e.clientX;
var width = absX - left;
var height = area / width;
elm.style.width = width + "px";
elm.style.height = height + "px";
}
}
function resizeH(e) {
elm.style.cursor = "n-resize";
document.body.style.cursor = "n-resize";
var top = parseInt(window.getComputedStyle(elm, null)["top"], 10);
document.onmouseup = stop;
document.onmousemove = function(e) {
var absY = e.clientY;
var height = absY - top;
var width = area / height;
elm.style.height = height + "px";
elm.style.width = width + "px";
}
}
})("box");
Fiddle
Though there's a small bug, I think. Couldn't fix it. When you resize the width it's ok, but when you resize the height, and then move the div, it lags or w/e. Check the fiddle. Other than this, it's working fine.

Mouse on left of screen move image to left, same when mouse on right of screen

I'm trying to get an image that is around 1920x1200px to pan around on a 800x600px browser window.
So if my mouse is on the top-left of the browser window the image is alined so it's top-left margins are on the top-left of the browser window. The same goes for the bottum-right.
So if the mouse is in the centre of the screen the image should be centered too.
Im not sure what calculations are needed as my math is a bit rusty.
Currently I'm using a bit of javascript that just moves the image using CSS's top/left properties but without much success as it's just moving the picture around from it's top/left corner.
I'v also set the image's position to absolute in css.
function updateImgPosition( e )
{
var avatar = document.getElementById("avatar");
// Width
var windowWidth = window.innerWidth;
var mouseWidthLocation = e.x;
var percentOfWidth = (100 / windowWidth) * mouseWidthLocation;
// Height
var windowHeight = window.innerHeight;
var mouseHeightLocation = e.y;
var percentOfHeight = (100 / windowHeight) * mouseHeightLocation;
avatar.style.top = percentOfHeight + "%";
avatar.style.left = percentOfWidth + "%";
}
document.onmousemove = updateImgPosition;
This is a demo of what I have: http://jsfiddle.net/uQAmQ/1/
Fiddle: http://jsfiddle.net/uQAmQ/2/
You should not "pan" on an absolutely positioned element, because the window's width and height keep changing according to the image. A smoother solution involves using a background image. See the middle of my answer for the used logic.
Consider this JavaScript (read comments; HTML + CSS at fiddle):
(function(){ //Anonymous function wrapper for private variables
/* Static variables: Get the true width and height of the image*/
var avatar = document.getElementById("avatar");
var avatarWidth = avatar.width;
var avatarHeight = avatar.height;
var windowWidth = window.innerWidth;
var windowHeight = window.innerHeight;
/* Logic: Move */
var ratioY = (avatarHeight - windowHeight) / windowHeight;
var ratioX = (avatarWidth - windowWidth) / windowWidth;
function updateImgPosition( e ) {
var mouseY = e.pageX; //e.pageX, NOT e.x
var mouseX = e.pageY;
var imgTop = ratioY*(-mouseY);
var imgLeft = ratioX*(-mouseX);
document.body.style.backgroundPosition = imgLeft + "px " + imgTop + "px";
}
/* Add event to WINDOW, NOT "document"! */
window.onmousemove = updateImgPosition;
})();
The logic behind it:
Relative units cannot be used, because the image size is specified in absolute units.
The offsets should change according to a specific ratio, which is similar to: image size divided by window size.However, this ratio is not complete: The image would disappear at the bottom/left corner of the window. To fix this, substract the window's size from the image's size. The result can be found in the code at variable ratioX and ratioY.
The previous code had to be loaded at the window.onload event, because the image's size was dynamically calculated. For this reason, a HTML element was also included in the body.
The same code can be written much smaller and efficient, by specifying the size of the background in the code. See this improved code. Fiddle: http://jsfiddle.net/uQAmQ/3/
(function(){ //Anonymous function wrapper for private variables
/* Static variables: Get the true width and height of the image*/
var avatarWidth = 1690;
var avatarHeight = 1069;
var windowWidth = window.innerWidth;
var windowHeight = window.innerHeight;
/* Logic: Move */
var ratioY = (avatarHeight - windowHeight) / windowHeight;
var ratioX = (avatarWidth - windowWidth) / windowWidth;
function updateImgPosition( e ) {
var mouseX = e.pageX; //e.pageX, NOT e.x
var mouseY = e.pageY;
var imgTop = ratioY*(-mouseY);
var imgLeft = ratioX*(-mouseX);
document.body.style.backgroundPosition = imgLeft + "px " + imgTop + "px";
}
/* Add event to WINDOW, NOT "document"! */
window.onmousemove = updateImgPosition;
})();
If you don't mind a decreased code readability, the following code is the best solution, Fiddle: http://jsfiddle.net/uQAmQ/4/:
(function(){ //Anonymous function wrapper for private variables
/* Static variables: Get the true width and height of the image*/
var windowWidth = window.innerWidth;
var windowHeight = window.innerHeight;
var ratioY = (windowHeight - 1069) / windowHeight;
var ratioX = (windowWidth - 1690) / windowWidth;
window.onmousemove = function( e ) {
document.body.style.backgroundPosition = ratioX * e.pageX + "px " + ratioY * e.pageY + "px";
}
})();

Categories

Resources