Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

355
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda