I'm trying to rotate an image 180 degrees counterclockwise every time the user click's the image's parent element. I'm using JQueryRotate v2.3.
My code:
$('.material').click(function () {
var thisPic = $(this).find('.fanpic');
thisPic.rotate({ animateTo: -180 });;
});
This works at first, but the image starts spinning clockwise with the second click onward. How can I fix this so the image always spins counterclockwise?
Try keeping the rotate value at somewhere for example in the parent element:
$('.material').click(function () {
if(!this.animateTo) this.animateTo = 0;
this.animateTo = this.animateTo + -180;
var thisPic = $(this).find('.fanpic');
thisPic.rotate({ animateTo: this.animateTo });;
});
Try this jsfiddle
Hope this helps,
Yo can keep a variable with the angle.
var angle = -180;
$('.material').click(function () {
var thisPic = $(this).find('.fanpic');
thisPic.rotate({ animateTo: angle });
angle -= 180;
});
Related
I am trying to make a simple game in which you can rotate each element by 90 degrees on each click with some transition like 500ms. When it passes from 270 to 0 it goes in opposite direction. It is possible to achieve this by keeping incrementing the value to +Infinity, but what if I want to keep the angle normalized, from 0 to 359? How do I tell browser to use closest path to rotate an object basically going from 270 to 360 and not from 270 to 0. What if someday I exceed the integer limit and it brakes? Is it even possible? Here is an example of how it works right now.
const images = document.querySelectorAll("img")
for(const image of images) {
let rotation = 0;
image.style.transition = 'transform 500ms';
image.addEventListener('click', function() {
rotation = (rotation + 90) % 360
image.style.transform = `rotate(${rotation}deg)`
})
}
No need to mod the angle by 360. Integer limit in JS is about 9007199254740991. So if you rotate 100 times per second, it's still would last 100,000 years or so.
const images = document.querySelectorAll("img")
for(const image of images) {
let rotation = 0;
image.style.transition = 'transform 500ms';
image.addEventListener('click', function() {
rotation = (rotation + 90)
image.style.transform = `rotate(${rotation}deg)`
})
}
<img src="https://picsum.photos/200">
[EDITED because I made progress]
I have this wheel with text that spans linearly.
Here's the JS Fiddle to show the visual and my code:
http://jsfiddle.net/DarcFiddle/F3gsD/10/
So I create a set:
paper.setStart();
// draw draw draw
var set = paper.setFinish();
Then here's a method to rotate it:
var degree = 0;
function rotateSet() {
degree = degree + 90;
set.animate({ transform: ["R", degree, canvasCenter, canvasCenter]}, 500 );
}
You can try this by clicking the "Rotate" button from the JSFiddle.
But as you can see, the element also rotate on its own center, which break the structure.
What can I do to prevent this?
Thanks
I did it with double rotation
http://jsfiddle.net/DarcFiddle/F3gsD/12/
So, I loop the set and do two r transformation. First one is the center of the circle and second one is rotate back only the text as suggested by Ian in the comment above.
set.forEach(function(e) {
var textDegree = Math.round( Raphael.angle(e.attr("x"), e.attr("y"), x, y) );
if(e.attr("text-anchor") === "end") {
textDegree = textDegree - 180;
}
e.animate({
transform: ["r", degree, x, y, "r", textDegree, e.attr("x"), e.attr("y")]
}, 500);
});
I want to create an effect that when I click on an image element, it will rotate the content inside it but not the element's width and height(My img is 400x300). I want the element dimensions stay but the image rotate. Compressing the height or the width of the image based on the position is fine with me, as long as it does not rotate the element itself.
I have tried jQueryRotate but it seems it's only rotating the element, not the image inside it.
Is there any plugin or way for me to rotate the image without rotating the element itself?
EDIT:
My code:
$('#rotate-btn').click(function (e) {
value += 90;
if (value == 90) {
var img = document.getElementById('image_canv');
var width = img.clientWidth;
var height = img.clientHeight;
$('#image_canv').height(height);
$('#image_canv').width(width); {
animateTo: value
}
}
$('#image_canv').rotate(value);
});
});
It does rotate the image, but the position of the element moves, so it's not working out.
i take image with id myimg wrap it in div and then rotate it.
http://jsfiddle.net/D5Sz8/
Be carefull all styles applied to image maybe needed to apply on div if you dont want them to rotate along the image.
jQuery.fn.rotate = function(degrees) {
$(this).css({'-webkit-transform' : 'rotate('+ degrees +'deg)',
'-moz-transform' : 'rotate('+ degrees +'deg)',
'-ms-transform' : 'rotate('+ degrees +'deg)',
'transform' : 'rotate('+ degrees +'deg)'});
};
var i= $('img'), d= document.createElement('div'), rotation=0;
d.id='myimg'; i[0].id='';
i.wrap(d);
$('#myimg').css({'display':'inline-block', 'overflow':'hidden'});
ani();
function ani (){
i.rotate(++rotation);
requestAnimationFrame(ani);
}
Ok, so I'm assuming that you have a global variable defined as value
You can use the following code to rotate by 90 degree increments if that is what you want:
var value = 0;
$('#rotate-btn').click(function (e) {
var element = $("#image_canv");
var startDegree = value;
var endDegree = value + 90;
value += 90;
$({ i:startDegree }).animate({ i: endDegree }, {
step: function(now,fx) {
element.css({transform : 'rotate('+ now + 'deg)' });
},
duration: 1000
});
});
And here is an example of it working: http://jsfiddle.net/hQHhf/4/
If you need to rotate by some other increment, than the code will need to be changed slightly to fit those needs. But basically, your value variable should always end up being the same as endDegree so that the next rotation will start at the proper place for the image.
Here's an example of how to use it if you are wanting to do varying degrees of rotation, both positive and/or negative (For this, I changed id of rotate-btn to a class instead, and gave it its own function for rotating on any degrees):
var value = 0;
$('.rotate-btn').click(function (e) {
doRotate($(this).val(), 1000);
});
function doRotate(degrees, delay) {
var element = $("#image_canv");
var startDegree = value;
var endDegree = value + parseInt(degrees);
value = value + parseInt(degrees);
$({ i:startDegree }).animate({ i: endDegree }, {
step: function(now,fx) {
element.css({transform : 'rotate('+ now + 'deg)' });
},
duration: delay
});
}
And here is an example: http://jsfiddle.net/hQHhf/6/
Also made some minor edits to the HTML as well, like using <button> instead of <input> to send a proper value to the doRotate function and some other minor edits.
Hope this helps you get the jist of it and apply it for your needs. Also, because you are setting a width of 400, and a height of 300 on the images, while chrome does not seem effected by this, but some other browsers like firefox will be. For example, as the image rotates, the size rotates with it, this is because you don't have an equal size on both width and height of your image, so it won't look as tho its rotating naturally in all browsers. If you give both, width and height, the same size you won't have this problem.
You can use this javascript code so you can rotate your image easily. But you have only to change the image destination.
var looper;
var degrees = 0;
function rotateAnimation(el,speed){
var elem = document.getElementById(el);
if(navigator.userAgent.match("Chrome")){
elem.style.WebkitTransform = "rotate("+degrees+"deg)";
} else if(navigator.userAgent.match("Firefox")){
elem.style.MozTransform = "rotate("+degrees+"deg)";
} else if(navigator.userAgent.match("MSIE")){
elem.style.msTransform = "rotate("+degrees+"deg)";
} else if(navigator.userAgent.match("Opera")){
elem.style.OTransform = "rotate("+degrees+"deg)";
} else {
elem.style.transform = "rotate("+degrees+"deg)";
}
looper = setTimeout('rotateAnimation(\''+el+'\','+speed+')',speed);
degrees++;
if(degrees > 359){
degrees = 1;
}
document.getElementById("status").innerHTML = "rotate("+degrees+"deg)";
}
And now use the HTML code for the image:
<img id="exe" style='position:absolute;left:450px;height:300px;' src="images/example.png" alt="exe">
And it's about to finish just add another script tag:
rotateAnimation("exe",30);
This function above will move the image 30deg you can change it to 40,50... and the "exe" is the id of the image.
Ok so i have this triangle div and when i click it, it only rotates 180deg. Ok so far so good but if i click it again it stays the same here is my code.
$('.Triangle').click(function()
{
var Location = $('.Triangle').offset().left;
$('#Account').css({"left" : Location});
$('#Account').slideToggle('fast');
$('.Triangle').css({"transform" : "rotate(180deg)"});
});
Transforms don't work that way (i.e. you can't apply it twice). You have to keep track of state:
$(".Triangle").on('click', function () {
if ($(this).data('flipped') {
$(this).data('flipped', false).css('transform', 'rotate(0deg)');
}
The 'transform' style sets the rotation of the element from it's original position. When you click it the first time, it rotates the element from 0deg to 180deg. When you click it again, it changes the rotation from 180deg to 180deg.
You need to keep a counter for the number of clicks and multiply that by your rate of rotation. Something like this should do the trick:
var count = 1;
$('.Triangle').click(function() {
var Location = $('.Triangle').offset().left;
$('#Account').css({"left" : Location});
$('#Account').slideToggle('fast');
$('.Triangle').css({"transform" : "rotate(" + (180 * count++) + "deg)"});
});`
var i = 0;
$('.Triangle').click(function() {
i++;
var Location = $('.Triangle').offset().left;
$('#Account').css({"left" : Location});
$('#Account').slideToggle('fast');
$('.Triangle').css({"transform" : "rotate(" + (i % 2 ? 0 : 180 + "deg)"});
});
I'm trying to do some simple camera rotation in WebGL app(using lesson 10 from Learning WebGL), but I'm definetly doing something wrong.. I mean the horizontal movement of camera seems good,movement with WASD seems also OK, but when I'm adding the vertical movement, in some points of the map, something goes wrong and the map starts to incline. Where is my mistake? (demo is here)
what I'm doing is:
function handleMouseMove(event) {
var canvas = document.getElementById("quak-canvas");
var newX = event.clientX;
var newY = event.clientY;
var newRotationMatrix = mat4.create();
mat4.identity(newRotationMatrix);
var deltaY = newY - lastMouseY;
mat4.rotate(newRotationMatrix, degToRad(deltaY / 40), [1, 0, 0]);
var deltaX = newX - lastMouseX;
horizontalAngle = (event.pageX/(canvas.width/2))*180;
mat4.rotate(newRotationMatrix, degToRad(deltaX / 3.75), [0, 1, 0]);
mat4.multiply(newRotationMatrix, moonRotationMatrix, moonRotationMatrix);
lastMouseX = newX
lastMouseY = newY;
window.moveBy(10, 10);
}
I think there is some translate is missing or something like, but I have tried some combinations but it wasn't successfull..
Thanks a lot
Serhiy.
First off, let me say that you're demo actually looks okay to me. Maybe it's a side effect of the dampened vertical rotation, but I don't see anything that looks too terribly off. Your code looks okay too for the most part. I think the core of your problem may be the matrix multiply at the end. The fact that you're always building off the previous frame's results can lead to some complications.
In my FPS movement code I re-calculate the view matrix every frame like so:
var viewMat = mat4.create();
mat4.identity(viewMat);
mat4.rotateX(viewMat, xAngle); // X angle comes from Y mouse movement
mat4.rotateY(viewMat, yAngle); // Y angle comes from X mouse movement
mat4.translate(viewMat, position);
The position is calculated when WASD are pressed like so:
var dir = vec3.create();
if (pressedKeys['W']) { dir[2] -= speed; }
if (pressedKeys['S']) { dir[2] += speed; }
if (pressedKeys['A']) { dir[0] -= speed; }
if (pressedKeys['D']) { dir[0] += speed; }
if (pressedKeys[32]) { dir[1] += speed; } // Space, moves up
if (pressedKeys[17]) { dir[1] -= speed; } // Ctrl, moves down
// Create an inverted rotation matrix to transform the direction of movement by
var cam = mat4.create();
mat4.identity(cam);
mat4.rotateY(cam, -yAngle);
mat4.rotateX(cam, -xAngle);
// Move the camera in the direction we are facing
mat4.multiplyVec3(cam, dir);
vec3.add(position, dir);
Hopefully that helps you get a working solution for your own code!