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

191
Visualizações
How to make object move in a triangle motion in Javascript canvas?

I've created a circle that I want to animate so that it moves in a triangle motion using if statements, and changing the y/x coordinates, but all I can make it do is go back and forth, so I was wondering if anyone could help?

the function where I'm changing the x/y parameters is called "triangle".

the full js code:

var canvas;
var ctx;
var w = 1000;
var h = 600;
var allCircles = [];



setUpCanvas();
createData(1);



 animationLoop();





function animationLoop(){
    clear();
    circlesDrawUpdate(allCircles);

    requestAnimationFrame(animationLoop);
}


function circlesDrawUpdate(a){
    for(var i=0; i<a.length; i++){
        circle(a[i]);
        triangle(a[i]);
    }
}

function createData(num){
    for (var i=0; i<num; i++){
        allCircles.push({
            "x": w/2,
            "y": h/2,
            "dx": randn(100),
            "dy": 3,
            "r": 50,
            "c":200+rand(180),
            "a": 0.5,
        })
    }
}





function triangle(o){
    var i;
    o.x += o.dx;
    o.y += o.dy;
    if(o.y = h){
        o.dy *= +1;
    }

    if(o.x> w || o.x < 0){
        o.dx *=-1;
    
    }
}


function clear(){
    ctx.clearRect(0,0,w,h);
}



function circle(o){
    ctx.beginPath();
    ctx.arc(o.x,o.y,o.r,0,2*Math.PI);
    ctx.fillStyle = "hsla("+o.c+", 100%, 50%, "+o.a+")";
    ctx.fill();
}

function randn(r){
    var result = Math.random()*r - r/2;
    return result;
}

function randi(r){
    var result = Math.floor(Math.random()*r);
    return result;
}

function rand(r){
    var result = Math.random()*r;
    return result;
}

function setUpCanvas(){
    canvas = document.querySelector("#myCanvas");
    ctx = canvas.getContext("2d");
    canvas.width = w;
    canvas.height = h;
    canvas.style.border ="5px dashed purple";
}




console.log("Module 7 Exercise");
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Is that what you meant by "triangle motion"?

function triangle(o) {
    o.x += o.dx;
    o.y += o.dy;
    if(o.y == h || o.y == 0){
        o.dy *= -1;
    }

    if(o.x >= w || o.x <= 0){
        o.dx *=-1;
    }
}

The reason why your circle kept going only back and forth is because first condition in your triangle function, where you assigned value ('=') instead of comparison ('=='). o.dy variable has been changed to h in every function call, therefore y value of your circle was always equal to canvas height.

Another problem is that you should multiply o.dy by -1 to change direction (same as you did in o.dx).

Last thing is checking both sides of your canvas (0 and h), not only the bottom one (h) (again, same as you did in o.dx)

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