How to paint an element in screen using javascript?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • shivajikobardan
    New Member
    • Jun 2022
    • 12

    How to paint an element in screen using javascript?

    Code:
    <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:

    Now, I want the bat to move left and right when I press arrow keys.
    Code:
    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=oldBatPositio n.x+batDirectio n.x
    newBatPosition. y=oldBatPositio n.y+batDirectio n.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.
Working...