1

I have been trying to make a Guitar String animation with sound and so far I have made the line flick and go up and down to simulate a guitar string pluck, but for some reason I can't make it do that twice. What I mean is first time I hover over the string it acts as it should, but second time I hover over it just the sound plays, but the string doesn't repeat the upwards/downwards motion. This is the code for the string:

  var canvas = document.getElementById('myCanvas');
  var context = canvas.getContext('2d');

  context.moveTo(0, 5);
  context.bezierCurveTo(0, 5, 250, 5, 500, 5);

  context.strokeStyle = '#00DFFF';
  context.stroke();
  var a=5; var interv = null;

  $(document).ready(function(){
    var beepOne = $("#beep-one")[0];
    $("#myCanvas")
      .mouseenter(function() {
        beepOne.play();
        interv = setInterval(pluck, 50);
      });
    });

    function pluck() {
          var x=5;
          if(a>0) a-=0.1; else if(a==0){ unpluck; a=5;} else a+=0.1;
          a=a*-1;
          x=x+a;
          canvas.width = canvas.width;
          context.moveTo(0, 5);
          context.bezierCurveTo(0, 5, 250, x, 500, 5);
          context.strokeStyle = '#00DFFF';
          context.stroke();
        }

  function unpluck() {
      clearInterval(interv);
  }

Can someone help with this issue?

pdw
  • 8,359
  • 2
  • 29
  • 41
  • 4
    Can you setup a fiddle to display your issue? – Sterling Archer Jul 16 '14 at 21:42
  • Do you want to reset `a = 5` in the `mouseenter` function? –  Jul 16 '14 at 21:50
  • Also, do you want to call `unpluck()`? Because it's just a statement that isn't called up. Another thing, `a` might not always hit `0`, because of how floating point arithmetic works. It could be something like 0.00000000001. This question might help: https://stackoverflow.com/questions/249467/what-is-a-simple-example-of-floating-point-rounding-error and read [this MDN article](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/round) on how to apply rounding to decimals. –  Jul 16 '14 at 21:51
  • I have fixed the issue. You were right @RalphWiggum, `a` never acctualy hits zero and that was on some 9th decimal, so I made it fixed with `toFixed` on 1 decimal. Now it works perfectly! Thanks for the idea! – Bogdan Kovačević Jul 17 '14 at 11:51

0 Answers0