Estoy trabajando en un juego simple usando lienzo HTML y JavaScript.
El lienzo es el siguiente: La parte del lienzo
Cuando la bola de color golpea los lados de la imagen (img 1 y 2 en la imagen de arriba), su color cambiará aleatoriamente.
Ahora, además quiero agregarle una función. Lo que quiero es que cuando la bola de color golpee el lado de la imagen, quiero cambiar img 1 y 2. ¿Cómo puedo hacer eso en mi código? He investigado un poco aquí y en YouTube, pero todavía no tengo idea. Mi código es el siguiente:
var canvas = document.getElementById("canvas_bb84_1"); canvas.width = 1000; var c = canvas.getContext("2d"); //Draw the image to the canvas var x = 220; var radius = 15; var color = "#0095DD"; function draw() { c.drawImage(p_fil, 100, 30, 100, 100); //img1 c.drawImage(p_fil_flip, 810, 30, 100, 100); //img2 c.drawImage(p_det_flip, 10, 30, 100, 100); c.drawImage(p_det, 900, 30, 100, 100); //Draw the ball c.beginPath(); c.arc(x, 80, radius, 0, Math.PI * 2, false); c.fillStyle = color; c.fill(); c.closePath(); } //Update the animation of the ball and collision detection var dx = 4; function update() { if (x + radius > 820 || x - radius < 190) { dx = -dx; color = "#" + ((1 << 24) * Math.random() | 0).toString(16); } x += dx; } //Initialize the images var p_det = new Image(); var p_det_flip = new Image(); var p_fil = new Image(); var p_fil_flip = new Image(); //Animate function animate() { p_det.src = "photon_detector.jpg"; p_det_flip.src = "photon_detector_flip.jpg" p_fil.src = "p_filter_02.jpg"; p_fil_flip.src = "p_filter_02_flip.jpg"; window.requestAnimationFrame(animate); c.clearRect(0, 0, canvas.width, canvas.height); draw(); update(); } animate();