HTML
<div id="enemy-area" class="enemy-area">
<canvas id="enemy-canvas"></canvas>
<div id="ea-1" class="ea"></div>
<div id="ea-2" class="ea"></div>
CSS
#enemy-area{
display: grid;
position: relative;
grid-template-columns: repeat(3, 1fr);
grid-auto-rows: minmax(20vh, 1fr);
gap: 5px;
text-align: center;
width: 35vh;
height: 60vh;
overflow: hidden;
margin: auto;
}
#enemy-canvas{
position: absolute;
top: 70%; /* Center vertically */
left: 50%; /* Center horizontally */
transform: translate(-50%, -50%);
width: 50%; /* Adjust based on desired size */
height: 50%; /* Adjust based on desired size */
z-index: 20;
pointer-events: none;
}
Java script
import Character from './Character.js';
export default class Enemy extends Character {
constructor(name, maxHP, HP, defense, imageSrc, healthBarId, team, type, statusHP, ATK, temporaryATK, temporaryDEF) {
super(name, maxHP, HP, defense, imageSrc, healthBarId, team, type, statusHP, ATK, temporaryATK, temporaryDEF);
this.name = name || 'Enemy';
this.maxHP = maxHP || 12;
this.HP = HP || 12;
this.defense = defense || 0;
this.imageSrc = imageSrc || '../texture/CHARACTER/enemy1.png';
this.healthBarId = healthBarId || 'enemy-health-bar';
this.team = team || 'enemy-area';
this.type = type || 'enemy-object';
this.statusHP = statusHP || 'enemy-hp';
this.ATK = ATK || 0;
this.temporaryATK = temporaryATK || 0;
this.temporaryDEF = temporaryDEF || 0;
// Animation properties
this.spriteWidth = 64;
this.spriteHeight = 64;
this.staggerFrames = 8;
this.gameFrame = 0;
this.scale = 2.9;
this.spriteAnimationsEnemy = {};
this.animationStates.forEach((state, index) => {
let frames = { loc: [] };
for (let j = 0; j < state.frames; j++) {
let positionX = j * this.spriteWidth;
let positionY = index * this.spriteHeight;
frames.loc.push({ x: positionX, y: positionY });
}
this.spriteAnimationsEnemy[state.name] = frames;
});
this.currentAnimation = 'wave,right'; // Default animation
// Load the sprite sheet
this.spriteSheet = new Image();
this.spriteSheet.src = this.imageSrc;
this.spriteSheet.onload = () => {
console.log(`Enemy sprite sheet loaded successfully: ${this.spriteSheet.src}`);
};
this.spriteSheet.onerror = () => {
console.error(`Failed to load sprite sheet: ${this.spriteSheet.src}`);
};
// Initialize canvas after DOM is ready
document.addEventListener('DOMContentLoaded', () => this.initializeCanvas());
}
// Initialize the canvas and its context
initializeCanvas() {
this.enemyElement = document.getElementById('enemy-canvas');
if (!this.enemyElement) {
console.error("Canvas element for enemy not found. Ensure the HTML contains a canvas with ID 'enemy-canvas'.");
return;
}
console.log(`Canvas element found: ${this.enemyElement.id}`);
const devicePixelRatio = window.devicePixelRatio || 1;
this.enemyElement.width = this.enemyElement.clientWidth * devicePixelRatio;
this.enemyElement.height = this.enemyElement.clientHeight * devicePixelRatio;
this.context = this.enemyElement.getContext('2d');
if (!this.context) {
console.error("Failed to initialize 2D context for enemy canvas.");
return;
}
this.context.scale(devicePixelRatio, devicePixelRatio);
this.context.imageSmoothingEnabled = false;
console.log("Canvas and context initialized successfully.");
}
// Animate the enemy
animateEnemy() {
if (!this.enemyElement || !this.context || !this.spriteSheet.complete) {
console.error("Animation prerequisites not met. Ensure canvas, context, and sprite sheet are properly initialized.");
return;
}
this.gameFrame++;
// Get the current animation and frame position
const animation = this.spriteAnimationsEnemy[this.currentAnimation];
if (!animation) {
console.error(`Animation state '${this.currentAnimation}' not found.`);
return;
}
const position = Math.floor(this.gameFrame / this.staggerFrames) % animation.loc.length;
const frame = animation.loc[position];
// Clear the canvas
this.context.clearRect(0, 0, this.enemyElement.width, this.enemyElement.height);
// Calculate scaled dimensions
const scaledWidth = Math.round(this.spriteWidth * this.scale);
const scaledHeight = Math.round(this.spriteHeight * this.scale);
// Center the image
const destX = (this.enemyElement.width - scaledWidth) / 2;
const destY = (this.enemyElement.height - scaledHeight) / 2;
// Draw the current frame
this.context.drawImage(
this.spriteSheet,
frame.x, frame.y, // Source frame (x, y)
this.spriteWidth, // Source frame width
this.spriteHeight, // Source frame height
destX, destY, // Destination (x, y)
scaledWidth, // Scaled width
scaledHeight // Scaled height
);
}
// Initialize the enemy and start animation
const enemy = new Enemy(
'Enemy',
80,
80,
0,
'../texture/CHARACTER/enemy1.png',
'enemy-health-bar',
'enemy-object',
'enemy-hp',
5,
0,
0
);
// Main animation loop
function animate() {
enemy.animateEnemy(); // Update the enemy's animation
requestAnimationFrame(animate); // Request the next frame
}
// Start the animation loop
animate();
these are the code for my game project, and it does not display the canvas on the screen, even if I inspect the webpage it is still not there. I really don’t know whats the problem, Im a total noob in JS, ple someone help
I tried changing or resizing the CSS, and also the JS especially below where you create and initialize the character, it actually works for the other character but it does not work for the enemy character. I tried copying the other character but the canvas is still not showing up