Ich habe bereits das Rechteck gezeichnet Ich muss nur nach dem Mauszeiger nach links bewegen. Ich weiß, dass der mouseMove und der Event-Listener falsch sind. Ich lasse sie nur für einen Startpunkt dort. Hier ist der Code:Wie kann ich ein Rechteck der mouseX-Position innerhalb der Zeichenfläche folgen lassen?
var canvas; //This variable will be use as a reference to the canvas object
var ctx; //A variable to hold the value of the context
var rectX = 100; //rect X pos
var rectY = 200; //rect Y pos
var rectWidth = 25; //width
var rectHeight = 25; //height
var rectSpeedX = 10;
var rectSpeedY = 10;
var rectX2 = 400; //rect X pos
var rectY2 = 790; //rect Y pos
var rectWidth2 = 100; //width
var rectHeight2 = 20; //height
const WIDTH = 1000; //Width of the canvas
const HEIGHT = 800; //Height of the canvas
function mouseMove(event) {
var rectX2 = clientX;
}
document.addEventListener("mousemove", mouseMove);
window.onload = function() {
canvas = document.getElementById("myCanvas");
ctx = canvas.getContext('2d');
var framesPerSecond = 30; //FPS
setInterval(function() {
drawEverything(); //Calling the rect function 30 FPS
movement();
}, 1000/framesPerSecond); //Calls the move and draw function using an inline function. 30 FPS 1000/30
}
function drawEverything() {
ctx.fillStyle = 'red' //Draws the white background every frame covering square
ctx.fillRect(0, 0, WIDTH, HEIGHT);
ctx.fillStyle = 'black'
ctx.fillRect(rectX, rectY, rectWidth, rectHeight); //redraws the recntangle each frame which gives the illusion of movement
ctx.fillRect(rectX2, rectY2, rectWidth2, rectHeight2)
}
function movement() {
rectX += rectSpeedX;
rectY += rectSpeedY;
if (rectX > WIDTH - 12.5 || rectX < 0) {
rectSpeedX = -rectSpeedX;
}
if (rectY > HEIGHT - 12.5 || rectY < 0) {
rectSpeedY = -rectSpeedY;
}
}
rectX2
* {
padding: 0;
margin: 0;
}
canvas {
background: #eee;
display: block;
margin: 0 auto;
}
<canvas id="myCanvas" width="1000" height="800"></canvas>