Reputation: 7
Made a 3d cube. When a button is clicked, it rotates 50 deg left or right. I want it rotate an additional 50deg further when I click the same button. How do I achieve this? Here is my code right now:
//code to rotate cube
var rotateCube = document.getElementById('cube');
var moveLeft = document.getElementById('button-one');
var moveRight = document.getElementById('button-two');
moveLeft.onclick = function() {
rotateCube.style.webkitTransform = "rotateY(-50deg)";
}
moveRight.onclick = function() {
rotateCube.style.webkitTransform = "rotateY(50deg)";
}
in full here: http://jsfiddle.net/camlatimer/6xp2dwe7/1/
I've searched around. There are examples like this one: http://paulrhayes.com/experiments/cube-3d/
But I'm new to programming (2 months of fiddling with javascript in my free time) and don't understand much. I thought I could complete my objective pretty easily, but I'm stuck. I don't want to use any plugins. Just want to learn to really program things on my own. Any help would be appreciated.
Upvotes: 0
Views: 1171
Reputation: 761
LcSalazar is correct in regards to handling to rotation state of your cube, but my impression is that you're also interested in animating the rotation? If so, you'll want to check out CSS animations to handle those in-between states. This question covers dynamic values in CSS keyframed animations, which might be a bit beyond your current knowledge of CSS/JS, but spend some time with it and you'll be surprised how quickly it starts making sense.
Good luck!
Upvotes: 1
Reputation: 16841
The problem is with your premise:
"When a button is clicked, it rotates 50 deg left or right"
Actually, when a button is clicked, you are setting the rotation to be exactly -50deg
or 50deg
. It's an absolute assignment, not an increment.
In order to increment (since the rotation property is assigned by a text composed value), you'd need to store the value in a way where you can control it. For example, storing it in an external variable, and use it to increment the final value.
Something like this:
//Here's where you will store the actual value
var rotationValue = 0;
moveLeft.onclick = function() {
rotationValue -= 50;
rotateCube.style.webkitTransform = "rotateY("+ rotationValue +"deg)";
}
moveRight.onclick = function() {
rotationValue += 50;
rotateCube.style.webkitTransform = "rotateY("+ rotationValue +"deg)";
}
Upvotes: 0