Код: Выделить всё
const canvas = document.getElementById('avatar-canvas');
const ctx = canvas.getContext('2d');
const sprite = new Image();
sprite.src = 'my_avi.png';
const spriteWidth = 60;
const spriteHeight = 160;
const directions = {
down: 0,
left: 1,
right: 2,
up: 3
};
let legFrames = [4, 5, 6, 7]; // footstep animation frames
let legFrame = 0;
let frame = 1; // Default idle frame is middle
let direction = directions.down;
let x = canvas.width / 2 - spriteWidth / 2;
let y = canvas.height - spriteHeight - 20;
let tick = 0;
let moving = false;
const keys = {};
// Draw avatar
function drawAvatar() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
const col = moving ? legFrames[legFrame % legFrames.length] : frame;
const row = direction;
ctx.drawImage(
sprite,
col * spriteWidth, row * spriteHeight,
spriteWidth, spriteHeight,
x, y,
spriteWidth, spriteHeight
);
}
// Animation loop
function update() {
tick++;
if (moving && tick % 10 === 0) {
legFrame++;
}
handleMovement();
drawAvatar();
requestAnimationFrame(update);
}
// Key listeners
window.addEventListener('keydown', e => {
keys[e.key.toLowerCase()] = true;
moving = true;
});
window.addEventListener('keyup', e => {
keys[e.key.toLowerCase()] = false;
if (!keys['arrowup'] && !keys['arrowdown'] && !keys['arrowleft'] && !keys['arrowright']
&& !keys['w'] && !keys['a'] && !keys['s'] && !keys['d']) {
moving = false;
legFrame = 0;
frame = 4; // Reset to idle frame
}
});
// Define world and TV boundary limits
const tvBlockHeight = canvas.height * 0.4; // Approx. top 40% blocked
const padding = 10; // Optional padding from edge
function handleMovement() {
let nextX = x;
let nextY = y;
if (keys['w'] || keys['arrowup']) {
nextY -= 2;
direction = directions.up;
} else if (keys['s'] || keys['arrowdown']) {
nextY += 2;
direction = directions.down;
}
if (keys['a'] || keys['arrowleft']) {
nextX -= 2;
direction = directions.left;
} else if (keys['d'] || keys['arrowright']) {
nextX += 2;
direction = directions.right;
}
// World boundary collisions
const maxX = canvas.width - spriteWidth - padding;
const maxY = canvas.height - spriteHeight - padding;
if (nextX >= padding && nextX = padding && nextY tvBlockHeight) {
y = nextY;
}
}
}
let animationStarted = false;
sprite.onload = () => {
drawAvatar();
if (!animationStarted) {
update();
animationStarted = true;
}
};
< /code>
[img]video-L.png[/img]
https://www.youtube.com/embed/xolgs4-mymQ?si=KgabkxW6n-67L0oM
MCR - Welcome to the Black Parade
Pierce The Veil - King For A Day
BMTH - Can You Feel My Heart
Подробнее здесь: https://stackoverflow.com/questions/796 ... javascript