0

I have a lucky wheel, with a spinning arrow that rotates randomly. The problem is that sometimes the arrow barely spins when clicked on, because (for example) if the first click gives the number 400 the arrow will in fact rotate 400 degrees but if the second click gives 380 the arrow will just go back 20 degrees, meaning it will barely move. So I suppose I need a way to make the various clicks add up ( 1st click - random number; 2nd click - 1st click result + random number and so on).

My code is the following:

CSS

    img {
    transition: transform 2s ease-out;
}

HTML

<div>
    <img src="34-200.png" />
</div>

JavaScript

<script>
    var img = document.querySelector('img');
img.addEventListener('click', onClick, false);


function onClick() {
    this.removeAttribute('style');

    var deg = 500 + Math.round(Math.random() * 4000);

    var css = 'transform: rotate(' + deg + 'deg);';

    this.setAttribute(
        'style', css
    );
}

</script>

Help!

  • Your `var deg = ` code seems perfectly fine, what _exactly_ is the problem? –  Apr 12 '17 at 11:10
  • @ChrisG The problem is that sometimes the arrow spins only a little, like only 20degrees, and I don't want that to happen. It needs to make at least one full rotation (360 degrees). – Tomás Miguel Apr 12 '17 at 11:15
  • @Chris I didn't know that. But I think you get what I meant. – Tomás Miguel Apr 12 '17 at 11:25
  • @Chris you are right, thanks. Already edited – Tomás Miguel Apr 12 '17 at 11:40
  • I believe @Chris is incorrect. The biggest problem here is that while setting the `` to `rotate(500)` will indeed cause roughly one and a half rotations, setting it to `rotate(480)` next will make the `` rotate 20 degrees backwards. –  Apr 12 '17 at 11:59
  • yeah @ChrisG is right, thanks. So I suppose now what I have to do is make the varios clicks add up instead of all of them start in 0. And I have no idea how. – Tomás Miguel Apr 12 '17 at 14:19
  • Here's one way: https://jsfiddle.net/y1qy9u8L/ –  Apr 12 '17 at 15:26
  • Also, the answer to the actual question is to pick a random value of at least 360. –  Apr 12 '17 at 15:29

1 Answers1

0

var angle = 0;

var blocked = false;

var wheel = document.querySelector('#wheel');
wheel.addEventListener('click', () => {
  if (blocked) return;

  var deg = 720 + Math.round(Math.random() * 2000);
  angle += deg;

  wheel.style.transform = "rotate(" + angle + "deg)";
  blocked = true;
  setTimeout(function() {
    blocked = false;
  }, 2100);
}, false);
.placeholder {
  display: block;
  width: 200px;
  height: 200px;
  background-color: red;
}

img {
  transition: transform 2s ease-out;
}
<img id="wheel" class="placeholder" >