我正试图让画布移向另一个画布 - JAVASCRIPT

时间:2016-04-08 22:16:55

标签: javascript html5 math canvas

我写了这段代码,试图让myCanvas转向myCanvas1。我尝试使用Math.atan2()方法执行此操作。但它不起作用。有任何想法吗? 请不要使用任何JQuery。

HTML:

<canvas id="myCanvas"></canvas>
<canvas id="myCanvas1"></canvas>

JS:

 var follower = document.getElementById('myCanvas');
    var flw = follower.getContext('2d');

    var runner = document.getElementById('myCanvas1');
    var rnr = runner.getContext('2d');

document.addEventListener('keydown', moveShot);

    //Cordinates of sPositions 1 and two
    var sPosition0 = [700, 700];
    var sPosition1 = [400, 400]; 

    var xPosition0 = sPosition0[0], yPosition0 = sPosition0[1];
    var xPosition1 = sPosition1[0], yPosition1 = sPosition1[1];

    //This should be the arctan between sPosition0 and sPosition1
    var angleRadians0 = Math.atan2(sPosition0[0] - sPosition1[0], sPosition0[1] - Position1[1]);

    /*The speed of the object is 4. To get it to move diagonally towards sPosition1 I need to divide dy with the angle arctan between the two objects */
    var dx = 4;
    var dy = 4 / angleRadians0;

    function moveShot(){
        // Deleting the "old" square
        flw.clearRect(0, 0, 700, 700);
      //Drawing the square at its appropriate position
      flw.fillRect(xPosition0, yPosition0, 100, 100);
      //Adding the movement after every frame
      xPosition0 += dx;
      yPosition0 += dy;
      setTimeout(moveShot, 20);
    }

CSS:

#myCanvas1{
  height: 100px;
  width: 100px;
  background-color: '#ff0000';
}

谢谢!

编辑: 至于究竟发生了什么,我很困惑。没有任何事情发生,我没有说,因为它是凌晨3点,我想有人会指出我做出的一些非常明显的错误,一切都会有所作为。那么,发生的事情是好的,什么都没有,我无法理解为什么。然而,再次,凌晨3点,我可能已经搞砸了,但我没看到。

这是一个小提琴https://jsfiddle.net/Snubben/15tf0svd/3/

0 个答案:

没有答案