1
respuesta

06 ¡Ya que va, que vuelva!

Código

<canvas width="600" height="400"> </canvas>

<style>
    canvas {
        border: 1px solid lightgrey;
    }
</style>
<script>
    const 
        canvasEl = document.querySelector( 'canvas' ),
        ctx = canvasEl.getContext( '2d' );

    ctx.fillStyle = 'lightgrey';
    ctx.fillRect( 0, 0, 600, 400 ); 

    ( () => {
        const
            radio = 20,
            width = 600,
            height = 400,
            time = 5;

        let 
            x = 0,
            y = 0;

        const drawCircle = ( x, y ,radio ) => {
            ctx.fillStyle = 'blue';
            ctx.beginPath();
            ctx.arc( x, y, radio, 0, 2 * Math.PI );
            ctx.fill();
        }

        const initialState = ( inicial_x, inicial_y ) => {
            if( inicial_x == 0 )        x = inicial_x + radio;
            if( inicial_y == 0 )        y = inicial_y + radio;
            if( inicial_x == width )    x = inicial_x - radio;
            if( inicial_y == height )   y = inicial_y - radio;

            drawCircle( x, y, radio, 10 );
        }

        const clearScreen = () => {
            ctx.clearRect( 0, 0, width, height );
        }

        const move = () => {
            clearScreen();
            drawCircle( x, y, radio );
        }

        const toLeft = () => {
            const id = setInterval( () => { 
                if( x < ( 0 + radio ) ) {
                    clearInterval( id );
                    toRight();

                    return;
                }

                move();
                x--;
            }, time );
        }

        const toRight = () => {        
            const id = setInterval( () => { 
                if( x > ( width - radio ) ) {
                    clearInterval( id );
                    toLeft();

                    return;
                }

                move();
                x++;
            }, time );
        }

        const start = () => setTimeout( () => {   
            toLeft();
        }, 3000 );

        initialState( 0, 0 );
        start();
    })();


</script> 

Resultado en mi CodePen

https://codepen.io/pen?template=poLavgm

1 respuesta

Hola Juan , espero que esté bien.

Gracias por compartir tu código con nosotros, yo teste y está correcto contínua con tu estudos :)

Si tienes alguna pregunta sobre el contenido de los cursos, estaremos aquí para ayudarte.

Te recomiendo que puedes interactuar con el resto de nuestros compañero por nuestro Discord.

En virtud de que en Discord el alcance es mayor, la interacción es inmediata y llega a más compañeros y el foro solo quedaría para esclarecer cualquier duda que puedas tener sobre el contenido de los cursos

De esa manera si tienes algún comentario, opinión, recomendación o algún consejo sea por el Discord, con certeza por ahí llegará a más personas

Si este post te ayudó, por favor, marca como solucionado ✓. Continúa con tus estudios