How to paint an element in screen using javascript?

Joined
Dec 11, 2022
Messages
11
Reaction score
1
JavaScript:
<div class="body">
    <div id="board">
      <div id="bat" class="bat"></div>
      <div id="ball" class="ball"></div>
    </div>
  </div>

This is my HTML.
I've done CSS For all of them and generated this:
hnrN3k8CBV2NYuAMWZW5YVh7aNbkwa_Oj5P5ZmEHWO3rkwv7NetQ0-UL4rotwlG2DCpiou4oxv1To1z8HS9oe2orZQ1D9Adv3VuZhKF2wilLhITlWxjekfS1cFkObOjC6tX_doWv37QRpFgfWPrgsTpelep9BMMcp24Uw8Qw0vuKJbvqH_5RBTCLwd7khQ

Now, I want the bat to move left and right when I press arrow keys.

JavaScript:
window.addEventListener("keydown", function (e) {

  switch (e.key) {
    case "ArrowLeft":
      batDir.x = -1;
      batDir.y = 0;
      paintBat(batDir.x, batDir.y);
      break;
    case "ArrowRight":
      batDir.x = 1;
      batDir.y = 0;
      paintBat(batDir.x, batDir.y);
      break;

  }
})

My goal is to paint the bat at new position. I'm wondering how to do it.

The logic should be

newBatPosition.x=oldBatPosition.x+batDirection.x
newBatPosition.y=oldBatPosition.y+batDirection.y

But what will do the job of painting newBatPosition.x and newBatPosition.y is what I'm not clear of. I'm not using canvas.

Plus, what'll be the oldBatPosition? I've used CSS to paint them. So, I'm wondering how do I get oldBatPosition coordinates as well.

I just made a similar project using tutorial and it's just disheartening that I can't make this project.

 
Joined
Jan 30, 2023
Messages
107
Reaction score
13
To paint the bat at a new position, you can use the style property of the div element with the id bat to update its left and top position. You'll need to keep track of the old position in variables.

Here's an updated code example

JavaScript:
const bat = document.getElementById("bat");
let oldBatPos = { x: 0, y: 0 };
let batDir = { x: 0, y: 0 };

window.addEventListener("keydown", function (e) {
  oldBatPos.x = parseInt(bat.style.left) || 0;
  oldBatPos.y = parseInt(bat.style.top) || 0;

  switch (e.key) {
    case "ArrowLeft":
      batDir.x = -1;
      batDir.y = 0;
      break;
    case "ArrowRight":
      batDir.x = 1;
      batDir.y = 0;
      break;
  }

  const newBatPos = {
    x: oldBatPos.x + batDir.x,
    y: oldBatPos.y + batDir.y
  };
  bat.style.left = `${newBatPos.x}px`;
  bat.style.top = `${newBatPos.y}px`;
});


Note: This code assumes that the bat's starting position is at (0, 0).
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,059
Latest member
cryptoseoagencies

Latest Threads

Top