I was following this MDN tutorial:
And I was wondering how could we control the ball's movement using mouse movement event.
I have seen that mousemove works with textarea and some inputs:
https://developer.mozilla.org/en-US/docs/Web/Events/mousemove
I thought if we could put a textarea behind the canvas, we could detect the event, get the mouse's position and let the user change the ball's movement with mouse movement.
I have read:
Dynamically resize textarea width and height to contain text
So I tried:
<!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>
The expected output would be to have the textarea using canvas' width and height, and being behind it; however it is smaller and put on top left:
Thank you for your help.