Delete item when a key is pressed

3

The code consists of creating a wolf with the arrows on the keyboard, I already made a functional code, but a wolf remains behind as if it were a wolf line.

How do I remove the wolf old as it were? That is, the wolf before the new one that is drawn when I press the key.

My code:

console.log("*script is working*");

var vp = document.getElementById("villaPlatzi");

var papel = vp.getContext("2d");

var flechas = {
	UP: 38,
	DOWN: 40,
	LEFT: 37,
	RIGHT: 39,
};

document.addEventListener("keyup", moverLobo);

function moverLobo(evento)
{
	papel.drawImage(lobo.objeto, xLobo, yLobo);
	var movimientoLobo = 10;
	switch(evento.keyCode)
	{
		case flechas.UP:
		yLobo = yLobo - movimientoLobo
		break;

		case flechas.DOWN:

		yLobo = yLobo + movimientoLobo
		break;

		case flechas.LEFT:

		xLobo = xLobo - movimientoLobo
		break;

		case flechas.RIGHT:

		xLobo = xLobo + movimientoLobo
		break;

		default:
		console.log("***************************************")
		break;
	}
}

var xLobo = 150;
var yLobo = 150;

var fondo = {
	url: "https://cdn.pixabay.com/photo/2015/06/23/13/51/pattern-818713_960_720.png",
	loadState: false,
};

fondo.objeto = new Image();
fondo.objeto.src = fondo.url;
fondo.objeto.addEventListener("load", cargarFondo);

var vaca = {
	url: "https://img.icons8.com/color/2x/cow.png",
	loadState: false,
};

vaca.objeto = new Image();
vaca.objeto.src = vaca.url;
vaca.objeto.addEventListener("load", cargarVaca);

var pollo = {
	url: "https://img.icons8.com/color/2x/chicken.png",
	loadState: false,
};

pollo.objeto = new Image();
pollo.objeto.src = pollo.url;
pollo.objeto.addEventListener("load", cargarPollo);

var cerdo = {
	url: "https://img.icons8.com/color/2x/pig.png",
	loadState: false,
};

cerdo.objeto = new Image();
cerdo.objeto.src = cerdo.url;
cerdo.objeto.addEventListener("load", cargarCerdo);

var lobo = {
	 url: "https://img.icons8.com/color/2x/wolf.png",
	 loadState: false,
};

lobo.objeto = new Image();
lobo.objeto.src = lobo.url;
lobo.objeto.addEventListener("load", cargarLobo)

function cargarFondo()
{
	fondo.loadState = true;
	dibujar();
}
function cargarVaca()
{
	vaca.loadState = true;
	dibujar();
}
function cargarCerdo()
{
	cerdo.loadState = true;
	dibujar();
}
function cargarPollo()
{
	pollo.loadState = true;
	dibujar();
}
function cargarLobo()
{
	lobo.loadState = true;
	moverLobo();
}
function dibujar(evento)
{
	if(fondo.loadState == true)
	{
		papel.drawImage(fondo.objeto, 0, 0);
	}
	if (vaca.loadState == true)
	{
		var cantidad = aleatorio(5, 20);
		console.log("Hay " + cantidad + "vacas!");
		for(var v = 0; v < cantidad; v++)
		{
			var x = aleatorio(0, 420);
			var y = aleatorio(0, 420);
			papel.drawImage(vaca.objeto, x, y);
		}
	}
	if (pollo.loadState == true)
	{
		var cantidad = aleatorio(5, 20);
		console.log("Hay " + cantidad + "pollos!");
		for(var p = 0; p < cantidad; p++)
		{
			var x = aleatorio(0, 420);
			var y = aleatorio(0, 420);
			papel.drawImage(pollo.objeto, x, y);

		}
	}
	if (cerdo.loadState == true)
	{
		console.log("Hay " + cantidad + "cerdos!");

		var cantidad = aleatorio(5, 20);
		for(var c = 0; c < cantidad; c++)
		{
			var x = aleatorio(0, 420);
			var y = aleatorio(0, 420);
			papel.drawImage(cerdo.objeto, x, y);
		}
	}
	if (lobo.loadState == true)
	{
		console.log("el lobo esta suelto :v");
		papel.drawImage(lobo.objeto, xLobo, yLobo);
	}
}
function aleatorio (min, max)
{
	var resulato;
	resultado = Math.floor(Math.random() * (max - min + 1)) + min;
	return resultado;
}
<canvas id ="villaPlatzi" width="400px" height="300px"></canvas>
    
asked by Danico Player 25.12.2018 в 00:46
source

2 answers

2

You only have to create the wolf each time you press the arrows, in this case when you release them, so as not to leave a trace. What it does is build the entire farm in motion poop. I hope it serves you, I've tried it and it works, you just have to add a cap if you do not want the wolf to get off the canvas.

var vp = document.getElementById("villaPlatzi")
var papel = vp.getContext("2d")
document.addEventListener("keyup", moverLobo)

var xLobo = 150
var yLobo = 100

var xVaca = new Array()
var yVaca = new Array()

var xCerdo = new Array()
var yCerdo = new Array()

var xPollo = new Array()
var yPollo = new Array()

function moverLobo(e) {
    var movimiento = 64
    var teclas =
        {
            LEFT: 37,
            UP: 38,
            RIGHT: 39,
            DOWN: 40
        }
    switch (e.keyCode) {
        case teclas.LEFT:
            xLobo = xLobo - movimiento
            dibujar(xLobo, yLobo)
            break
        case teclas.UP:
            yLobo = yLobo - movimiento
            dibujar(xLobo, yLobo)
            break
        case teclas.RIGHT:
            xLobo = xLobo + movimiento
            dibujar(xLobo, yLobo)
            break
        case teclas.DOWN:
            yLobo = yLobo + movimiento
            dibujar(xLobo, yLobo)
            break
    }
}

var fondo =
    {
        url: "tile.png",
        carga: false
    }

var lobo =
    {
        url: "lobo.png",
        carga: false
    }

var vaca =
    {
        url: "vaca.png",
        carga: false
    }

var pollo =
    {
        url: "pollo.png",
        carga: false
    }

var cerdo =
    {
        url: "cerdo.png",
        carga: false
    }

lobo.imagen = new Image()
lobo.imagen.src = lobo.url
lobo.imagen.addEventListener("load", cargaLobo)

fondo.imagen = new Image()
fondo.imagen.src = fondo.url
fondo.imagen.addEventListener("load", cargaFondo)

vaca.imagen = new Image()
vaca.imagen.src = vaca.url
vaca.imagen.addEventListener("load", cargaVaca)

cerdo.imagen = new Image()
cerdo.imagen.src = cerdo.url
cerdo.imagen.addEventListener("load", cargaCerdo)

pollo.imagen = new Image()
pollo.imagen.src = pollo.url
pollo.imagen.addEventListener("load", cargaPollo)

function cargaLobo() {
    lobo.carga = true
    dibujar()
}

function cargaFondo() {
    fondo.carga = true
    dibujar()
}

function cargaPollo() {
    pollo.carga = true
    mantenerPosicion()
}

function cargaCerdo() {
    cerdo.carga = true
    mantenerPosicion()
}

function cargaVaca() {
    vaca.carga = true
    mantenerPosicion()
}

function mantenerPosicion() {
    if (vaca.carga) {
        var cantidad = aleatorio(1, 5)
        for (var i = 0; i < cantidad; i++) {
            var x = aleatorio(0, 6)
            var y = aleatorio(0, 6)
            x = x * 70
            y = y * 70
            xVaca[i] = x
            yVaca[i] = y
        }
    }
    if (cerdo.carga) {
        var cantidad = aleatorio(1, 5)
        for (var i = 0; i < cantidad; i++) {
            var x = aleatorio(0, 6)
            var y = aleatorio(0, 6)
            x = x * 70
            y = y * 70
            xCerdo[i] = x
            yCerdo[i] = y
        }
    }
    if (pollo.carga) {
        var cantidad = aleatorio(1, 10)
        for (var i = 0; i < cantidad; i++) {
            var x = aleatorio(0, 6)
            var y = aleatorio(0, 6)
            x = x * 70
            y = y * 70
            xPollo[i] = x
            yPollo[i] = y
        }
    }
    dibujar()
}

function dibujar() {
    if (fondo.carga) {
        papel.drawImage(fondo.imagen, 0, 0)
    }
    if (vaca.carga) {
        for (var i = 0; i < 10; i++) {
            papel.drawImage(vaca.imagen, xVaca[i], yVaca[i])
        }
    }
    if (cerdo.carga) {
        for (var i = 0; i < 10; i++) {
            papel.drawImage(cerdo.imagen, xCerdo[i], yCerdo[i])
        }
    }
    if (pollo.carga) {
        for (var i = 0; i < 10; i++) {
            papel.drawImage(pollo.imagen, xPollo[i], yPollo[i])
        }
    }
    if (lobo.carga) {
        papel.drawImage(lobo.imagen, xLobo, yLobo)
    }
}

function aleatorio(max, min) {
    var numero_aleatorio = Math.floor(Math.random() * (max - min + 1)) + min
    return numero_aleatorio
}
    
answered by 25.12.2018 / 02:54
source
0

I see that there is already an answer. This is mine.

  • it is necessary to check that all the images are loaded before drawing, otherwise you could find the background on top of the images. An easy way to do it is to put the images inside the HTML and use the event window.onload If you do not want to see the images you can hide them inside the canvas tag - for example.

  • When you want to move things on the canvas, with each step you have to erase everything and re draw it. To do this you need to use the clearRect : papel.clearRect(0, 0, vp.width, vp.height); method After deleting everything you need to redraw everything, and cows and pigs and chickens have to stay in the same position if you do not want to move them. For this you need to first create them and store them in an array of pigs, cows and chickens. For this I have created the functions function crearVacas , crearPollos . . .

  • var vp = document.getElementById("villaPlatzi");
    var papel = vp.getContext("2d");
    vp.width = 420;
    vp.height = 420;
    
    var xLobo = 150;
    var yLobo = 150;
    var movimientoLobo = 10;
    
    var flechas = {
      UP: 38,
      DOWN: 40,
      LEFT: 37,
      RIGHT: 39
    };
    
    var vacas = [];
    var pollos = [];
    var cerdos = [];
    
    document.addEventListener("keyup", moverLobo);
    
    function moverLobo(evento) {
      papel.clearRect(0, 0, vp.width, vp.height);
    
      switch (evento.keyCode) {
        case flechas.UP:
          yLobo = yLobo - movimientoLobo;
          break;
    
        case flechas.DOWN:
          yLobo = yLobo + movimientoLobo;
          break;
    
        case flechas.LEFT:
          xLobo = xLobo - movimientoLobo;
          break;
    
        case flechas.RIGHT:
          xLobo = xLobo + movimientoLobo;
          break;
    
        default:
          console.log("***************************************");
          break;
      }
    
      dibujar();
    }
    
    function dibujar() {
      papel.drawImage(fondo, 0, 0);
      for (var v = 0; v < vacas.length; v++) {
        papel.drawImage(vaca, vacas[v][0], vacas[v][1]);
      }
      for (var p = 0; p < pollos.length; p++) {
        papel.drawImage(pollo, pollos[p][0], pollos[p][1]);
      }
      for (var c = 0; c < cerdos.length; c++) {
        papel.drawImage(cerdo, cerdos[c][0], cerdos[c][1]);
      }
      papel.drawImage(lobo, xLobo, yLobo);
    }
    
    window.onload = function(e) {
      crearVacas();
      crearPollos();
      crearCerdos();
    
      dibujar();
    };
    
    function crearVacas() {
      var cantidad = aleatorio(2, 5);
      //console.log("Hay " + cantidad + "vacas!");
      for (var v = 0; v < cantidad; v++) {
        var x = aleatorio(0, 380);
        var y = aleatorio(0, 380);
        vacas.push([x, y]);
      }
    }
    
    function crearPollos() {
      var cantidad = aleatorio(2, 5);
      //console.log("Hay " + cantidad + "pollos!");
      for (var p = 0; p < cantidad; p++) {
        var x = aleatorio(0, 380);
        var y = aleatorio(0, 380);
        pollos.push([x, y]);
      }
    }
    
    function crearCerdos() {
      //console.log("Hay " + cantidad + "cerdos!");
      var cantidad = aleatorio(2, 5);
      for (var c = 0; c < cantidad; c++) {
        var x = aleatorio(0, 380);
        var y = aleatorio(0, 380);
        cerdos.push([x, y]);
      }
    }
    
    function aleatorio(min, max) {
      var resulato;
      resultado = Math.floor(Math.random() * (max - min + 1)) + min;
      return resultado;
    }
    canvas{border:1px solid}
    <canvas id ="villaPlatzi" width="400px" height="300px">
    <img id="fondo" src="https://cdn.pixabay.com/photo/2015/06/23/13/51/pattern-818713_960_720.png" />
    <img id="vaca" src="https://img.icons8.com/color/2x/cow.png" />
    <img id="cerdo" src="https://img.icons8.com/color/2x/pig.png" />
    <img id="pollo" src="https://img.icons8.com/color/2x/chicken.png" />
    <img id="lobo" src="https://img.icons8.com/color/2x/wolf.png" />
    </canvas>

    I hope it's useful

        
    answered by 25.12.2018 в 19:53