выдели только 1 функцию которая дает программе передвигать фигру const canvas =…
- User
выдели только 1 функцию которая дает программе передвигать фигру const canvas = document.getElementById('canvas'); const ctx = canvas.getContext('2d'); let squares = [{x: 50, y: 50, size: 50, color: 'red'}, {x: 150, y: 50, size: 50, color: 'blue'}, {x: 250, y: 50, size: 50, color: 'green'}]; let selectedSquare = null; let mousePosition = null;
canvas.addEventListener('mousedown', (event) => { mousePosition = {x: event.offsetX, y: event.offsetY}; selectedSquare = squares.find(square => { return mousePosition.x >= square.x && mousePosition.x <= square.x + square.size && mousePosition.y >= square.y && mousePosition.y <= square.y + square.size; }); });
canvas.addEventListener('mousemove', (event) => { if (selectedSquare) { selectedSquare.x = event.offsetX - mousePosition.x + selectedSquare.x; selectedSquare.y = event.offsetY - mousePosition.y + selectedSquare.y; mousePosition = {x: event.offsetX, y: event.offsetY}; } });
canvas.addEventListener('mouseup', () => { selectedSquare = null; });
function draw() { ctx.clearRect(0, 0, canvas.width, canvas.height); squares.forEach(square => { ctx.fillStyle = square.color; ctx.fillRect(square.x, square.y, square.size, square.size); }); }
function update() {}
function loop() { update(); draw(); requestAnimationFrame(loop); }
loop();
- Assistant
Функция, которая дает программе передвигать фигуру, это функция "mousemove". Она обрабатывает событие перемещения мыши и изменяет координаты выбранного квадрата в зависимости от координат мыши.
- User
сделай так. чтобы куд останавливался когда я беру его мышкой.const canvas = document.getElementById('canvas'); const ctx = canvas.getContext('2d'); //добавил ,чтобы поле программы подстраивалось под размер окна. const cols = canvas.width = window.innerWidth; const rows = canvas.height = window.innerHeight; //--------------------------------------------------- const colors = ['red', 'blue', 'green','orange']; const size = 7; const speed = 4; const maxSpeed = 10; const acceleration = 0.5;
let squares = [];
function Square(x, y, color, dx, dy) { this.x = x; this.y = y; this.color = color; this.dx = dx; this.dy = dy; this.size = size; }
Square.prototype.draw = function() { ctx.fillStyle = this.color; ctx.fillRect(this.x, this.y, this.size, this.size); };
Square.prototype.update = function() { this.x += this.dx; this.y += this.dy;
if (this.x <= 0 || this.x + this.size >= canvas.width) { this.dx = -this.dx; this.color = colors[Math.floor(Math.random() * colors.length)]; } if (this.y <= 0 || this.y + this.size >= canvas.height) { this.dy = -this.dy; this.color = colors[Math.floor(Math.random() * colors.length)]; } for (let i = 0; i < squares.length; i++) { const square = squares[i]; if (this !== square) { if (this.x < square.x + square.size && this.x + this.size > square.x && this.y < square.y + square.size && this.y + this.size > square.y) { if (this.color !== square.color) { const tempDx = this.dx; const tempDy = this.dy; this.dx = square.dx; this.dy = square.dy; square.dx = tempDx; square.dy = tempDy; this.color = colors[Math.floor(Math.random() * colors.length)]; square.color = colors[Math.floor(Math.random() * colors.length)]; } else { this.size += square.size; squares.splice(i, 1); } } } } if (this.dx > maxSpeed) { this.dx = maxSpeed; } if (this.dy > maxSpeed) { this.dy = maxSpeed; } this.dx <= acceleration; this.dy >= acceleration;};
function init() { for (let i = 0; i < 50; i++) { const x = Math.random(2) * (canvas.width - size); const y = Math.random() * (canvas.height - size); const color = colors[Math.floor(Math.random() * colors.length)]; const dx = Math.random() * speed + 2 - speed; const dy = Math.random() * speed + 2 - speed;
squares.push(new Square(x, y, color, dx, dy)); }}
function animate() { requestAnimationFrame(animate); ctx.clearRect(325, 700, canvas.width, canvas.height); ctx.fillStyle = "rgba(0, 30, 20, 0.08)"; ctx.fillRect(0, 0, cols, rows);
for (let i = 0; i < squares.length; i++) { squares[i].draw(); squares[i].update(); }} //добавил чтобы можно было передвигать куб canvas.addEventListener('mousedown', (event) => { mousePosition = {x: event.offsetX, y: event.offsetY}; selectedSquare = squares.find(square => { return mousePosition.x >= square.x && mousePosition.x <= square.x + square.size && mousePosition.y >= square.y && mousePosition.y <= square.y + square.size; }); });
canvas.addEventListener('mousemove', (event) => { if (selectedSquare) { selectedSquare.x = event.offsetX - mousePosition.x + selectedSquare.x; selectedSquare.y = event.offsetY - mousePosition.y + selectedSquare.y; mousePosition = {x: event.offsetX, y: event.offsetY}; } }); canvas.addEventListener('mouseup', () => { selectedSquare = null; }); function draw() { ctx.clearRect(0, 0, canvas.width, canvas.height); squares.forEach(square => { ctx.fillStyle = square.color; ctx.fillRect(square.x, square.y, square.size, square.size); }); }//----------------------------------------------------- init(); animate();
- Assistant
Для того, чтобы квадрат останавливался при захвате мышью, вам уже есть обработчики событий mousedown, mousemove и mouseup.
Вам нужно добавить переменную 'selectedSquare' и хранить в ней ссылку на квадрат, который был выбран мышью в обработчике события mousedown. Затем в обработчике события mousemove вы должны проверить, что переменная 'selectedSquare' не равна null, и если это так, то переместить выбранный квадрат по координатам мыши.
В обработчике события mouseup после перемещения квадрата вы должны сбросить переменную 'selectedSquare', чтобы выбранный квадрат снова мог двигаться при наведении на него мышью.
Примерный код для реализации этого функционала:
let selectedSquare = null; canvas.addEventListener('mousedown', (event) => { mousePosition = {x: event.offsetX, y: event.offsetY}; selectedSquare = squares.find(square => { return mousePosition.x >= square.x && mousePosition.x <= square.x + square.size && mousePosition.y >= square.y && mousePosition.y <= square.y + square.size; }); }); canvas.addEventListener('mousemove', (event) => { if (selectedSquare) { selectedSquare.x = event.offsetX - mousePosition.x + selectedSquare.x; selectedSquare.y = event.offsetY - mousePosition.y + selectedSquare.y; mousePosition = {x: event.offsetX, y: event.offsetY}; } }); canvas.addEventListener('mouseup', () => { selectedSquare = null; });