Jump to content

How to paint an element in screen using javascript?


polaryeti

Recommended Posts

 

<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.

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.

 

https://codepen.io/pelko/pen/jOpBmPN


 

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.