Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

356
Vistas
p5.js mouseclick move over Canvas

I am trying to solve a school assignment in p5 JavaScript. I want something to move over the canvas after one mouseclick. But it only moves a little bit and I have to click several times to get it all the way over. What have I done wrong? Shouldn't the loop make it move all the way? Can post the whole code if needed.

function CanvasPressed()

{
  
  if ( mouseX > 0 && mouseX < 638 && mouseY > 0 && mouseY < 100 )
  {
    
    Bird.stop();
    Bird.play();

    for ( let b = 640; b > 0; b--)
    {
     x = x - 0.05;
    }
          
  } 
   
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Alright, so you've got a couple misunderstood things, here:

// purely aesthetic but in javascript functions are usually written as (i think) camelCase
// so: canvasPressed() rather than CanvasPressed(), Class-es start with upper case
function CanvasPressed()
{
  // you can check for width & height if you want if ( mouseX > 0 && mouseX < width)
  if ( mouseX > 0 && mouseX < 638 && mouseY > 0 && mouseY < height )
  {

    for ( let b = 640; b > 0; b--) // this, in this case, does the same as for(let i = 0; i < width; i ++)
    {
     x += 0.05
     // 0.05 is very little, only a very small part of a pixel
    }
    // here it moves 0.05 * 640 (0.05 + 0.05 + 0.05 ... )
          
  }
}

javascript naming conventions thingy if you want

and this is how i would make it move through the canvas:

let mouseWasPressed = false;
let x = 20

function draw() {
  background(20);
  ellipse(x, height / 2, 40)
  
  if(mouseWasPressed) // don't need {} for 1 line after the if()
    x ++; // x = x + 1   shortening in javascript
  // }
}

function mousePressed(){
  mouseWasPressed = true
}

if you don't want the "animation" you could use your previous method, but change the 0.05 to 1:

for(let i = 0; i <= width; i ++) // you don't have to add parentheses for 1 line
   x ++;     // x = x + 1   just a shortening in javascript

OR just

 x = width // or x += width (x = x + width)
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda