This is a problem where firefox works just fine, while chrome has the problem. Opera has additional problems I need to adress and IExplore I haven’t bothered testing yet (don’t care right now to be quite honest).
I have an experiment going, where I rotate a picture of a car seen from above using JqueryRotate (sets the rotation of an element) and the left right arrow keys. The car is set to the center using javascript/jquery(works – no problem). If the up arrow is used, the car moves up in the direction it points – here is where the problem occurs. Don’t mind the fact that you can’t turn and drive at the same time, this will be fixed, no prob. But the picture moves a bit after I have turned it and then move forward? Why?
the javascript:
var angle = 0;
var degreeInRadians = 2*Math.PI/360;
var realX = 0;
var realY = 0;
$(document).ready(function(){
placeInCenter($("#carImage"));
});
$(document).keydown(function(e){
//left
if (e.keyCode == 37) {
rotateLeft($("#carImage"));
return false;
}
//up
if (e.keyCode == 38) {
moveForward($("#carImage"),1);
return false;
}
//right
if (e.keyCode == 39) {
rotateRight($("#carImage"));
return false;
}
//down
if (e.keyCode == 40) {
//TODO move the car forward
return false;
}
});
function placeInCenter(element) {
// get viewport height and width and divide it by 2
centerY = window.innerHeight/2;
centerX = window.innerWidth/2;
//set absoulte positioning on element
$(element).css("position", "absolute");
// place the element
$(element).offset({ top: centerY, left: centerX });
//update realX and realY
realX = centerX;
realY = centerY;
}
function rotateRight(element) {
if(angle <360) {
angle++;
}
else {
angle=0;
}
element.rotate(angle);
}
function rotateLeft(element) {
if(angle > 0) {
angle--;
}
else {
angle=359;
}
element.rotate(angle);
}
function moveForward(element, speed) {
//move the element to polar cordinate (speed,angle)
realX = realX + Math.cos(degreeInRadians * angle);
realY = realY + Math.sin(degreeInRadians * angle);
$(element).offset({ top: realY, left: realX });
}
The problem is that WebKit seems to set offset from the bounding box of the rotated element, while Firefox offsets it from the original bounding box, and then applies the rotation.
Place your finger at the corner of the car, rotate it, and then move it forward. The upper left corner of the car’s bounding box (its furthest left and top points after rotation) will line up with your finger.
It seems to works fine in Firefox and WebKit if you use
.css({ top: ... left: })instead of.offset(), and set the following css style:Demo: http://jsfiddle.net/jtbowden/2aeyP/2/