1

Someone please can help me with an object moving automatically when I click on the right arrow in canvas.

My code is

if(e.keyCode == 39) {
    bullet.x = +5;  
    setTimeout(function() {
        ctx.clearRect(0,0,canvas.width,canvas.height)
        ctx.drawImage(player.Image, player.x, player.y , player.width, player.height);
        ctx.drawImage(bullet.Image , bullet.x , bullet.y , bullet.width ,  bullet.height);
    }, 300);
    console.log("DOWN");
}

What do I need to add for the object moving by the right arrow?

Kate Orlova
  • 3,225
  • 5
  • 11
  • 35
Noam Plays
  • 11
  • 1
  • Possible duplicate of [How to use arrow keys to move object smoothly in canvas](https://stackoverflow.com/questions/39806858/how-to-use-arrow-keys-to-move-object-smoothly-in-canvas) – Kate Orlova Jun 21 '19 at 22:13
  • But he too didn't do automatically moving I want t do when I click in the first time its moves automatically right – Noam Plays Jun 21 '19 at 22:18

1 Answers1

0

It is necessary to use ClearReact to advance with the function setInterval ()

let canvas = document.getElementById("mycanvas");
let ctx = canvas.getContext('2d');
juego();
let ev;
let x = 0;

let base_image = new Image();
base_image.src = 'https://img.icons8.com/pastel-glyph/2x/search.png';
window.onkeydown = function(e) {
  this.ev = e;
}

function draw() {
  if (typeof this.ev != 'undefined' && this.ev.keyCode == 39) {
    x = x + 10;
    ctx.clearRect(0, 0, canvas.width, canvas.height)
    ctx.drawImage(base_image, x, 10);
  }
}

function juego() {

  pat = ctx.createPattern(canvas, "repeat");
  window.setInterval(draw, 500);
}
canvas {
  outline: black 3px solid;
}
<canvas id="mycanvas" width="150" height="150"></canvas>

for try press left arrow