javascript,使用鼠标控制球的运动

时间:2018-04-07 20:24:26

标签: javascript html css canvas

我正在关注此MDN教程:

https://developer.mozilla.org/es/docs/Games/Workflows/Famoso_juego_2D_usando_JavaScript_puro/Mueve_la_bola

我想知道如何使用鼠标移动事件来控制球的运动。

我已经看到mousemove可以使用textarea和一些输入:

https://developer.mozilla.org/en-US/docs/Web/Events/mousemove

我想如果我们可以在画布后放一个textarea,我们可以检测到事件,获取鼠标的位置,让用户通过鼠标移动来改变球的运动。

我读过:

Dynamically resize textarea width and height to contain text

所以我试过了:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Juego</title>
    <style>
        * {
            padding: 0;
            margin: 0;
        }

        canvas {
            background: #eee;
            display: block;
            margin: 0 auto;
        }
    </style>
</head>
<body>
<textarea name="ta" id="ta" cols="30" rows="10"></textarea>
<canvas id="myCanvas" width="480" height="320"></canvas>

<script>
    const textarea = document.getElementById('ta');
    const canvas = document.getElementById('myCanvas');
    const ctx = canvas.getContext('2d');

    textarea.style.height = canvas.height;
    textarea.style.width = canvas.width;

    let x = canvas.width / 2;
    let y = canvas.height - 30;

    const dx = 2;
    const dy = -2;

    let drawBall = function () {
        ctx.beginPath();
        ctx.arc(x, y, 10, 0, Math.PI * 2);
        ctx.fillStyle = "#0095DD";
        ctx.fill();
        ctx.closePath();
    };

    function draw(e) {
        console.log(e);
        ctx.clearRect(0,0,canvas.width,canvas.height);
        drawBall();

        x += dx;
        y += dy;
    }

    setInterval(draw, 10);

    canvas.addEventListener('mousemove', draw);


</script>
</body>
</html>

预期的输出是让textarea使用画布的宽度和高度,并在其后面;但是它更小并且放在左上角:

enter image description here

感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

您不需要textarea来捕获该事件,并且它会变得复杂,因为canvas将位于顶部且textarea将永远不会知道鼠标移动到它上面,并且为了让球随着鼠标移动,你必须将鼠标的xy传递到draw();,而它是“{1}}。移动功能

这是一个小提琴:https://jsfiddle.net/vqdyLx5u/22/

&#13;
&#13;
let canvas = document.getElementById('myCanvas');
let ctx = canvas.getContext('2d');

function drawBall(x, y) {
  ctx.beginPath();
  ctx.arc(x, y, 10, 0, Math.PI * 2);
  ctx.fillStyle = "#0095DD";
  ctx.fill();
  ctx.closePath();
}

function draw(x, y) {
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  drawBall(x, y);
}

draw(canvas.height / 2 , canvas.width / 2); // initial draw

canvas.addEventListener('mousemove', function(e) {
  draw(e.pageX, e.pageY); // the coordinates of the mouse
});
&#13;
* {
  padding: 0;
  margin: 0;
}

canvas {
  background: #eee;
  display: block;
  margin: 0 auto;
}
&#13;
<canvas id="myCanvas" width="480" height="320"></canvas>
&#13;
&#13;
&#13;