css3 rotate according to cursor - javascript

I am trying to do the following:
Create a square div on the screen and whenever the cursor is hovering it, the square should horizontally rotate (rotateY).
This is what I have done:
http://jsbin.com/ujolop/1/edit
HTML:
<div class="a"></div>
CSS:
.a {
width: 200px;
height: 200px;
background-color: green;
}
JavaScript:
var maxRotate = 30; //deg
$('.a').on('mousemove', function(event) {
var $this = $(this),
width = $this.width(),
center = width / 2,
left = $this.position().left,
curRelPosX = event.clientX - left,
percent = (curRelPosX - center) / center,
rotate = percent * maxRotate;
$this.css('transform', 'rotateY(' + rotate + 'deg)');
});
This isn't work. It jumps and most of the time doesn't respond to the cursor hover.
Any ideas?
UPDATE
If I am right, for unknown reasons this is working fine in firefox but doesn't working good in chrome. Any idea why? Do I use the correct event (mousemove)?

I edited some of the calculation in your JavaScript :
left = $this.parent().offset().left,
curRelPosX = event.pageX - left,
percent = (curRelPosX <= center) ? curRelPosX / center : (width - curRelPosX) / center
If you console.log(left) you can see there is a problem of accuracy, the code above is also better to determine the exact curRelPosX.
About the percent calculation, if you go further than the center (maximum rotation), the rotation should decrease from its maximum to zero at the left edge of the div.
I also included your div.a inside another div.c because the mousemove event wasn't working properly after you apply the css rotation.
Here is the edit of your jsbin.

Apparently somebody has been giving a lot of edits to this.
http://jsbin.com/ujolop/30/edit
The simplest fix was to change the axis you are rotating around. Secondly, you might have to use proprietary prefixes for some browsers, but maybe not what Vucko proposed, as IIRC, .css uses the DOM oriented camel case style properties, not the dash properties.
Edit: If you really want to rotate it around the vertical axis (coplanar with the screen), I suppose you might need your thing that's being rotated be different from the thing that's receiving the events.
There's more than one way to do it, but, take a look at
http://jsbin.com/ujolop/39/edit

Related

Zoom image given x and y

I have an image which as a "ruler" (made of basic divs positioned absolute on top of the image) that are use to measure the ends of the image. Now the idea is that if you long press one of the ruler ends (the dots at the end of the line which are draggable), the image in the background would zoom in that point, and follow the dot if the user moves it. I am able to detect the long press but I cannot get the image to zoom and follow the dot once detected. The code below is where I have done the detection and now I should apply the styling to move the image. I thought of using the transition property but couldn't get it to zoom on the dot. Any help is appreciated...
Here's a codesandbox with how the ruler works: Link
Meaningful code:
const x = get('x', varToUse); //This just gives the x coordinate of the ruler end
const y = get('y', varToUse); //This just gives the y coordinate of the ruler end
const image = ruler.current.parentElement.parentElement.childNodes[1].childNodes[1];
if (zoom) {
image.style.transform = `translate(${x * 2}px, ${y * 2}px) scale(2.0)`;
} else {
image.style.transform = `scale(1.0)`;
}
This is what the ruler looks like just to get an understanding:
You can make the image a div with background-image.
.image {
background-image: url({image_url});
}
so this way you can update the image size and position easily with this properties
.image {
background-size: x y;
background-position x y;
}
I think this way is easier to do the image resizing and zoom abilities.
another way is to use a canvas library that can help you a lot they have lots of built in functions.
I think trying it without library is better for now but as it grows try to move to a canvas library
The first reason is that in the code you provided, the DOM element that is being manipulated is a div id='root'. The image should be selected.

Properly centering div based on child element

This is a repost from StackExchange's GameDev section, yet, I find that the problem seems more applicable to StackOverflow because it pertains more to CSS, JS, and positioning techniques rather than JavaScript topics (mostly UnityScript and Phaser) discussed on the former.
I've been making a roguelike-style game in HTML5 without using canvas (only divs) with pure JS (fiddle!). I've been trying to enlarge the tile size (font size) while keeping the player centered within the camera. For some reason, when the tile size isn't equal to the map size, the camera will be slightly off.
Note that the 3D effect is on purpose; I believe it adds some much needed depth, and just looks super cool. :D
When tileScale (line 4 in the fiddle) is 9 (very undesirable; the dots on the player's y axis should be aligned, not at a slight angle):
When tileScale is 25 (on point!):
Here's some relevant (trimmed) code:
window.onresize = function(){
game.viewportWidth = Math.max(document.documentElement.clientWidth, window.innerWidth || 0);
game.viewportHeight = Math.max(document.documentElement.clientHeight, window.innerHeight || 0);
game.windowSize = Math.min(game.viewportWidth, game.viewportHeight);
// Droid Sans Mono has a ratio of 3:4 (width:height), conveniently.
// This may be problematic. I'm not sure.
game.tileWidth = game.windowSize*.6 / game.tileScale;
game.tileHeight = game.windowSize*.8 / game.tileScale;
}
// Update the camera position (needs help?)
this.updateCamera = function(){
// Get player coordinates (-.5 because we need to get the player tile center)
// times the tileWidth plus the game window (inner square) size divided by two.
var left = ((-game.player.x-.5)*game.tileWidth+game.windowSize/2)+"px";
var top = ((-game.player.y-.5)*game.tileHeight+game.windowSize/2)+"px";
game.planeContainer.style.left = left;
game.planeContainer.style.top = top;
}
How can I ensure that the dots in the center of the screen will be always lined up, instead of on a slight angle? My current evidence suggests that the position of the game.planeContainer object isn't being established correctly.
I know this is a super-tough problem, so any help will be greatly appreciated. Thanks in advance!
(Another fiddle link, in case you skimmed over the first one. :D)
Remove this line from your css stylings on .inner-text to take out the skew:
transform: translate(-50%, -50%);

Zoom-in and Zoom-out image when Mouse Scroll

I want to zoom-in and zoom-out image on mouse scroll in HTML. There are multiple img tag without ID. So how can I do it using JavaScript or Ajax?
Just throwing the answer for the ones that will search for an answer to this question.
First, you will need to find a system to detect the mouse scroll.
If you are courageous, you can develop it yourself.
If you're not, you can find some pretty good libraries (ex : MouseWheel with JQuery).
Next, you will find another two ways to zoom in and out.
Easy way
First, let's cheat a bit.
When you will have to zoom, just multiply the height and width of your image by a factor you will decide.
To have height and width into a variable (JQuery)
var height = $('#image').height();
var width = $('#image').width();
For each scroll you will receive, you will only have 2 choices.
Once you are able to know if the mousewheel goes up or down, you will just have to do something like this (JQuery)
height *= 2;
width *= 2;
This way, by doubling the size of your image, you will have the impression to zoom in.
Less easy way
If you want to zoom in as you would do in a GMap object, you can do something like that.
var firstHeight = $('#image').height();
height *= 2;
width *= 2;
scalechange = (actualHeight / firstHeight) - 1;
offsetX = -(coordX * scalechange);
offsetY = -(coordY * scalechange);
$("#image").css('top', offsetY + 'px');
$("#image").css('left', offsetX + 'px');
First, you have to have the first height of your image.
Next, you will double the size of your image (zoom effect).
Next step is to calculate the scalechange. You will be able to find multiple explanations and many way to calculate it, my method is as good as another.
The two offsets presented are the new positions that your image will adopt (simple factor calculation, it's like making x percent on a price).
Last part is to set the new values of your image.
In the end, you will be able to zoom and unzoom with ou without centering the image at your mouse position.
Be careful : The calculation above in only to zoom-in. You will have to do some maths to get the zoom-out!
Go further ?
Another way to go further would be to place your image in a div.
<div id="imageContainer" style="overflow:hidden;">
<img id="image" src="YourImage">
</div>
By setting
"overflow:hidden;"
to your div, your image will zoom.
But everything that will overflow your div will be hidden.
If you set your div to the original size of your image, like this (JQuery)
$("#imageContainer").css('height', $('#image').height());
$("#imageContainer").css('width', $('#image').width());
Then you will have an image displayed that will always be at the same size, but your zoom will be effective.
If you combine this to a drag'n'drop method, you have a GMap object-like (zoom in-out, moove the zoomed image, ...)
Hope it will help someone!

How to get the MouseEvent coordinates for an element that has CSS3 Transform?

I want to detect where a MouseEvent has occurred, in coordinates relative to the clicked element. Why? Because I want to add an absolutely positioned child element at the clicked location.
I know how to detect it when no CSS3 transformations exist (see description below). However, when I add a CSS3 Transform, then my algorithm breaks, and I don't know how to fix it.
I'm not using any JavaScript library, and I want to understand how things work in plain JavaScript. So, please, don't answer with "just use jQuery".
By the way, I want a solution that works for all MouseEvents, not just "click". Not that it matters, because I believe all mouse events share the same properties, thus the same solution should work for all of them.
Background information
According to DOM Level 2 specification, a MouseEvent has few properties related to getting the event coordinates:
screenX and screenY return the screen coordinates (the origin is the top-left corner of user's monitor)
clientX and clientY return the coordinates relative the document viewport.
Thus, in order to find the position of the MouseEvent relative to the clicked element content, I must do this math:
ev.clientX - this.getBoundingClientRect().left - this.clientLeft + this.scrollLeft
ev.clientX is the coordinate relative to the document viewport
this.getBoundingClientRect().left is the position of the element relative to the document viewport
this.clientLeft is the amount of border (and scrollbar) between the element boundary and the inner coordinates
this.scrollLeft is the amount of scrolling inside the element
getBoundingClientRect(), clientLeft and scrollLeft are specified at CSSOM View Module.
Experiment without CSS Transform (it works)
Confusing? Try the following piece of JavaScript and HTML. Upon clicking, a red dot should appear exactly where the click has happened. This version is "quite simple" and works as expected.
function click_handler(ev) {
var rect = this.getBoundingClientRect();
var left = ev.clientX - rect.left - this.clientLeft + this.scrollLeft;
var top = ev.clientY - rect.top - this.clientTop + this.scrollTop;
var dot = document.createElement('div');
dot.setAttribute('style', 'position:absolute; width: 2px; height: 2px; top: '+top+'px; left: '+left+'px; background: red;');
this.appendChild(dot);
}
document.getElementById("experiment").addEventListener('click', click_handler, false);
<div id="experiment" style="border: 5px inset #AAA; background: #CCC; height: 400px; position: relative; overflow: auto;">
<div style="width: 900px; height: 2px;"></div>
<div style="height: 900px; width: 2px;"></div>
</div>
Experiment adding a CSS Transform (it fails)
Now, try adding a CSS transform:
#experiment {
transform: scale(0.5);
-moz-transform: scale(0.5);
-o-transform: scale(0.5);
-webkit-transform: scale(0.5);
/* Note that this is a very simple transformation. */
/* Remember to also think about more complex ones, as described below. */
}
The algorithm doesn't know about the transformations, and thus calculates a wrong position. What's more, the results are different between Firefox 3.6 and Chrome 12. Opera 11.50 behaves just like Chrome.
In this example, the only transformation was scaling, so I could multiply the scaling factor to calculate the correct coordinate. However, if we think about arbitrary transformations (scale, rotate, skew, translate, matrix), and even nested transformations (a transformed element inside another transformed element), then we really need a better way to calculate the coordinates.
The behaviour you are experiencing is correct, and your algorithm isn't breaking. Firstly CSS3 Transforms are designed not to interfere with the box model.
To try and explain...
When you apply a CSS3 Transform on an element. the Element assumes a kind of relative positioning. In that the surrounding elements are not effected by the transformed element.
e.g. imagine three div's in a horizontal row. If you apply a scale transform to decrease the size of the centre div. The surrounding div's will not move inwards to occupy the space that was once occupied the transformed element.
example: http://jsfiddle.net/AshMokhberi/bWwkC/
So in the box model, the element does not actually change size. Only it's rendered size changes.
You also have to keep in mind that you are applying a scale Transform, so your elements "real" size is actually the same as it's original size. You are only changing it's perceived size.
To explain..
Imagine you create a div with a width of 1000px and scale it down to 1/2 the size. The internal size of the div is still 1000px, not 500px.
So the position of your dots are correct relative to the div's "real" size.
I modified your example to illustrate.
Instructions
Click the div and keep you mouse in the same position.
Find the dot in the wrong position.
Press Q, the div will become the correct size.
Move your mouse to find the dot in the correct position to where you clicked.
http://jsfiddle.net/AshMokhberi/EwQLX/
So in order to make the mouse clicks co-ordinates match the visible location on the div, you need to understand that the mouse is giving back co-ordinates based on the window, and your div offsets are also based on its "real" size.
As your object size is relative to the window the only solution is to scale the offset co-ordinates by the same scale value as your div.
However this can get tricky based on where you set the Transform-origin property of your div. As that is going to effect the offsets.
See here.
http://jsfiddle.net/AshMokhberi/KmDxj/
Hope this helps.
if element is container and positioned absolute or relative,
you can place inside of it element,
position it relative to parent and
width = 1px, height = 1px, and move to inside of container,
and after each move use document.elementFromPoint(event.clientX, event.clientY) =))))
You can use binary search to make it faster.
looks terrible, but it works
http://jsfiddle.net/3VT5N/3/ - demo
BY FAR the fastest. The accepted answer takes about 40-70 ms on my 3d transforms site, this usually takes less than 20 (fiddle):
function getOffset(event,elt){
var st=new Date().getTime();
var iterations=0;
//if we have webkit, then use webkitConvertPointFromPageToNode instead
if(webkitConvertPointFromPageToNode){
var webkitPoint=webkitConvertPointFromPageToNode(elt,new WebKitPoint(event.clientX,event.clientY));
//if it is off-element, return null
if(webkitPoint.x<0||webkitPoint.y<0)
return null;
return {
x: webkitPoint.x,
y: webkitPoint.y,
time: new Date().getTime()-st
}
}
//make full-size element on top of specified element
var cover=document.createElement('div');
//add styling
cover.style.cssText='height:100%;width:100%;opacity:0;position:absolute;z-index:5000;';
//and add it to the document
elt.appendChild(cover);
//make sure the event is in the element given
if(document.elementFromPoint(event.clientX,event.clientY)!==cover){
//remove the cover
cover.parentNode.removeChild(cover);
//we've got nothing to show, so return null
return null;
}
//array of all places for rects
var rectPlaces=['topleft','topcenter','topright','centerleft','centercenter','centerright','bottomleft','bottomcenter','bottomright'];
//function that adds 9 rects to element
function addChildren(elt){
iterations++;
//loop through all places for rects
rectPlaces.forEach(function(curRect){
//create the element for this rect
var curElt=document.createElement('div');
//add class and id
curElt.setAttribute('class','offsetrect');
curElt.setAttribute('id',curRect+'offset');
//add it to element
elt.appendChild(curElt);
});
//get the element form point and its styling
var eltFromPoint=document.elementFromPoint(event.clientX,event.clientY);
var eltFromPointStyle=getComputedStyle(eltFromPoint);
//Either return the element smaller than 1 pixel that the event was in, or recurse until we do find it, and return the result of the recursement
return Math.max(parseFloat(eltFromPointStyle.getPropertyValue('height')),parseFloat(eltFromPointStyle.getPropertyValue('width')))<=1?eltFromPoint:addChildren(eltFromPoint);
}
//this is the innermost element
var correctElt=addChildren(cover);
//find the element's top and left value by going through all of its parents and adding up the values, as top and left are relative to the parent but we want relative to teh wall
for(var curElt=correctElt,correctTop=0,correctLeft=0;curElt!==cover;curElt=curElt.parentNode){
//get the style for the current element
var curEltStyle=getComputedStyle(curElt);
//add the top and left for the current element to the total
correctTop+=parseFloat(curEltStyle.getPropertyValue('top'));
correctLeft+=parseFloat(curEltStyle.getPropertyValue('left'));
}
//remove all of the elements used for testing
cover.parentNode.removeChild(cover);
//the returned object
var returnObj={
x: correctLeft,
y: correctTop,
time: new Date().getTime()-st,
iterations: iterations
}
return returnObj;
}
and also include the following CSS in the same page:
.offsetrect{
position: absolute;
opacity: 0;
height: 33.333%;
width: 33.333%;
}
#topleftoffset{
top: 0;
left: 0;
}
#topcenteroffset{
top: 0;
left: 33.333%;
}
#toprightoffset{
top: 0;
left: 66.666%;
}
#centerleftoffset{
top: 33.333%;
left: 0;
}
#centercenteroffset{
top: 33.333%;
left: 33.333%;
}
#centerrightoffset{
top: 33.333%;
left: 66.666%;
}
#bottomleftoffset{
top: 66.666%;
left: 0;
}
#bottomcenteroffset{
top: 66.666%;
left: 33.333%;
}
#bottomrightoffset{
top: 66.666%;
left: 66.666%;
}
It essentially splits the element into 9 squares, determines which one the click was in via document.elementFromPoint. It then splits that into 9 smaller squares, etc until it is accurate to within a pixel. I know I over-commented it. The accepted answer is several times slower than this.
EDIT: It is now even faster, and if the user is in Chrome or Safari it will use a native function designed for this instead of the 9 sectors thingy and can do it consistently in LESS THAN 2 MILLISECONDS!
another way is place 3 divs in corners of that element,
than find transform matrix ... but is also works only for positioned containerable
elements – 4esn0k
demo: http://jsfiddle.net/dAwfF/3/
Also, for Webkit webkitConvertPointFromPageToNode method can be used:
var div = document.createElement('div'), scale, point;
div.style.cssText = 'position:absolute;left:-1000px;top:-1000px';
document.body.appendChild(div);
scale = webkitConvertPointFromNodeToPage(div, new WebKitPoint(0, 0));
div.parentNode.removeChild(div);
scale.x = -scale.x / 1000;
scale.y = -scale.y / 1000;
point = webkitConvertPointFromPageToNode(element, new WebKitPoint(event.pageX * scale.x, event.pageY * scale.y));
point.x = point.x / scale.x;
point.y = point.y / scale.x;
To get the coordinates of a MouseEvent relative to the clicked element, use offsetX / layerX.
Have you tried using ev.layerX or ev.offsetX?
var offsetX = (typeof ev.offsetX == "number") ? ev.offsetX : ev.layerX || 0;
See also:
CSSOM View Module: 9 Extensions to the MouseEvent Interface
IE 8 measures clientX from the element's padding edge instead of the content edge: GTalbot MSIE 8 Browser Bugs: event.offsetX, event.offsetY as mouse coordinates inside element target's padding-box
MSDN: offsetX Property
This seems to work really well for me
var elementNewXPosition = (event.offsetX != null) ? event.offsetX : event.originalEvent.layerX;
var elementNewYPosition = (event.offsetY != null) ? event.offsetY : event.originalEvent.layerY;
EDIT: my answer is untested, WIP, I will update when I get it working.
I'm implementing a polyfill of the geomtetry-interfaces. The DOMPoint.matrixTransform method I will make next, which means we should be able to write something like the following in order to map a click coordinate onto a transformed (possiblly nested) DOM element:
// target is the element nested somewhere inside the scene.
function multiply(target) {
let result = new DOMMatrix;
while (target && /* insert your criteria for knowing when you arrive at the root node of the 3D scene*/) {
const m = new DOMMatrix(target.style.transform)
result.preMultiplySelf(m) // see w3c DOMMatrix (geometry-interfaces)
target = target.parentNode
}
return result
}
// inside click handler
// traverse from nested node to root node and multiply on the way
const matrix = multiply(node)
const relativePoint = DOMPoint(clickX, clickY, 0, 800).matrixTransform(matrix)
relativePoint will be the point relative to the element's surface that you clicked on.
A w3c DOMMatrix can be constructed with a CSS transform string argument, which makes it super easy to use in JavaScript.
Unfortunately, this isn't working yet (only Firefox has a geometry-interfaces implementation, and my polyfill does not yet accept a CSS transform string). See: https://github.com/trusktr/geometry-interfaces/blob/7872f1f78a44e6384529e22505e6ca0ba9b30a4d/src/DOMMatrix.js#L15-L18
I will update this once I implement that and have a working example. Pull requests welcome!
EDIT: the value 800 is the scene's perspective, I'm not sure if this is what the fourth value for the DOMPoint constructor should be when we intend to do something like this. Also, I'm not sure if I should use preMultiplySelf or postMultiplySelf. I'll find out once I get it at least working (values may be incorrect at first) and will update my answer.
I am working on a polyfill to transfrom DOM coordinates. The GeometryUtils api is not available yet (#see https://drafts.csswg.org/cssom-view/). I created a "simple" code in 2014 to transform coordinates, like localToGlobal, globalToLocal and localToLocal. Its not finished yet, but its working :) I think I will finish it in the coming months (05.07.2017), so if you still need a API to accomplish coordinate transformation give it a try: https://github.com/jsidea/jsidea jsidea core library. Its not stable yet (pre alpha).
You can use it like that:
Create your transform instance:
var transformer = jsidea.geom.Transform.create(yourElement);
The box model you want to transform to (default:"border", will be replaced by ENUM's later on):
var toBoxModel = "border";
The box model where your input coordinates coming from (default:"border"):
var fromBoxModel = "border";
Transform your global coordinates (here {x:50, y:100, z: 0}) to local space. The resulting point has 4 components: x, y, z and w.
var local = transformer.globalToLocal(50, 100, 0, toBoxModel, fromBoxModel);
I have implemented some other functions like localToGlobal and localToLocal.
If you want to give a try, just download the release build and use the jsidea.min.js.
Download the first release here: Download TypeScript code
Feel free to change the code, I never put it under any license :)
I have this issue and started trying to compute the matrix.
I started a library around it: https://github.com/ombr/referentiel
$('.referentiel').each ->
ref = new Referentiel(this)
$(this).on 'click', (e)->
input = [e.pageX, e.pageY]
p = ref.global_to_local(input)
$pointer = $('.pointer', this)
$pointer.css('left', p[0])
$pointer.css('top', p[1])
What do you think ?
Works fine whether relative or absolute :) simple solution
var p = $( '.divName' );
var position = p.position();
var left = (position.left / 0.5);
var top = (position.top / 0.5);

Rotate sprite javascript

I have a sprite animation, a small cannon rendered using a 3D app. I have exactly 360 frames for a 360 degree turn. Each image has a 100x100 pixel size.
So basically what I am trying todo is when I click anywhere in the page, the barrel of the cannon needs to rotate to point at the mouse cursor, sound simple maybe but I can't really get it to work very well, perhaps cause my math skills is lacking :P
What I currently have is something like this
/* This is my div with the cannon background image (360 images stitched into one) each "image area" is 100x100px */
obj.cannon = $('#cannon');
/* Get the X/Y of the cannon loc in the dom */
var cannonX = $(obj.cannon).offset().left;
var cannonY = $(obj.cannon).offset().top;
/* Get radians using atan2 */
var radians = Math.atan2(e.pageY-cannonY, e.pageX-cannonX);
/* Convert to degrees */
var degrees = radians * (180/Math.PI);
And this is where I am, I mean since the image width is 100px and I need to move the background-position by 100px to move the cannon one degree right, because 360 images * 100px = 36000px in total. So the stitched sprite is like 36000px wide.
So
Insert weird calculation here based on the current backgroundPosition of the image-sprite and apply new backgroundPosition based on where you click with the mouse cursor, then use some sort of setTimeout(animateIt, speed); to "animate" the background position to the new position.
function animateIt(){
if(newpos!=targetpos) { //Use < > here if we need to add or remove
newpos+=100; //Until we arrive at the new backgroundPosition
$(obj.cannon).css({backgroundPosition: newpos+'px' });
setTimeout(animateIt, speed);
}
}
Am I at all on the right track here, am I thinking correctly about this? I feel stupid, this should be a simple thing but right now I am having a brain meltdown I think =P. My problem is I don't know how to properly arrive at the "new target backgroundposition" and then animate it ++ or -- based on the current background position :/
Well, here is a simplified working example with 10 images.
I'll post the code and jsFiddle now, and I might come back later to cover it in depth. But basically you just order your images correctly, and then you pick the segment by using (Segments - Math.floor(degree / (360 / segments))). You may have to adjust your 0 degree. For example, I made my 0 equal to what would normal by 90.
Pay attention to the fact that the screen coordinates, x and y, increase right and down. This makes the degrees of atan work clockwise instead of the usual counter clockwise in coordinate systems where x and y increase right and up.
I added in some text output that shows the degrees and image segment being shown.
jQuery handles normalizing the x and y position nicely. Just take care that your CSS setup is cross browser.
Working jsFiddle example
Here's our image:
Here's our HTML:
<div id="main"><div id="img"></div></div>
<div id="info">
<span></span><br/>
<span></span>
</div>
​
CSS:
div#main {
width:500px;
height:500px;
border:2px #000 solid; }
div#img {
width:94px;
height:119px;
overflow:hidden;
top:50%;
left:50%;
margin-left:-45px;
margin-top:-60px;
position:relative;
background-image:url('http://imgur.com/3UPki.png');
background-position:0;}
div#info {
position: absolute;
bottom:0;
left:0; }
​
Javascript / jQuery:
$(function() {
var position = $("div#img").position(),
mouseX, mouseY, imgX, imgY, degree;
imgX = position.left;
imgY = position.top;
$("#main").mousemove(function(e) {
// degree is arctan y over x (soh,cah,toa)
degree = Math.atan2((e.pageY - imgY),(e.pageX - imgX))*(180 / Math.PI);
degree = (degree - 90) % 360;
// jQuery normalizes pageX and pageY
// transfrom from -180 to 180 ==> 0 to 360
if (degree < 0) degree = 180 + (180 - (Math.abs(degree)));
rotate(degree);
$("span:first").html("Segment: " + (9 - Math.floor(degree / 36)));
$("span:last").html("Degree: " + Math.floor(degree));
});
function rotate(degree) {
var off = 9 - Math.floor(degree / 36);
$("div#img").css("background-position",-off*94);
}
}); ​
Working jsFiddle example
Keep in mind that the degrees you get from atan will start pointing right for zero degrees and go clockwise from there (-90 is up, 90 is down).
Each position of your image should correspond to a specific angle. Once you have the degrees measured (it looks like you have that part right), use some type of mapping to translate your degrees to the proper image offset. I don't know what your image looks like so I can't help with that. Assuming your image starts pointing right, and goes around clockwise from there, the degrees will correspond directly the the offset for the right image. (I suggest you arrange your frames like this for ease...)

Categories

Resources