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

175
Vistas
How can i use useState in React js?

I want to work this simple code in gatsby js(https://developer.mozilla.org/en-US/docs/Games/Tutorials/2D_Breakout_game_pure_JavaScript/Bounce_off_the_walls).

but the ball didn't work. I think the usage of useState is wrong. but I cannot find the wrong point. could you please help me? Thank you

javascript

import * as React from "react"
import {useRef, useEffect, useState} from "react";
import { Container, CanvasBox} from "./style"


const MainView = () => {
  let canvasRef = useRef(null)
  const [x, setValx] = useState(0);
  const [y, setValy] = useState(0);

  useEffect(()=>{
    const canvas = canvasRef.current;
    const context = canvas.getContext('2d');
    let ballRadius = 2;
    let xtemp = canvas.width/2;
    let ytemp = canvas.height-30;
    // console.log('xtemp')
    // console.log(xtemp)
    // console.log(ytemp)
    setValx(xtemp);
    setValy(ytemp);
    let dx = 2;
    let dy = -2;

    function drawBall() {
      context.beginPath();
      context.arc(x, y, ballRadius, 0, Math.PI*2);
      context.fillStyle = "white";
      context.fill();
      context.closePath();
    }

    function draw() {
      context.clearRect(0, 0, canvas.width, canvas.height);
        drawBall();

        if(x + dx > canvas.width-ballRadius || x + dx < ballRadius) {
            dx = -dx;
        }
        if(y + dy > canvas.height-ballRadius || y + dy < ballRadius) {
            dy = -dy;
        }

        // console.log('x')
        let xtemp = x + dx
        let ytemp = y + dy;
        console.log('x')
        console.log(x)
        console.log('xtemp')
        console.log(xtemp)
        setValx(xtemp);
        setValy(ytemp);
    }  
    setInterval(draw, 10);
  },[x,y])


  return(
    <>
      <Container>
        <CanvasBox ref={canvasRef} ></CanvasBox>
      </Container>
    </> 
  )
}

export default MainView

css

import styled from "@emotion/styled"


export const Container = styled.div`
    background-color: black;
    margin: 0;
    width: 100vw;
    height: 100vmax;
    max-height: 100vh;
`
export const CanvasBox = styled.canvas`
    width: 100%;
    height: 100%;
    position: absolute;
`

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

It was So amazing , I spend some time on it and I found it But it's not done yet.

but maybe you can complete it . I have to say when you set you (x,y) you cant expect x or y have that value then I change them to xtemp or ytemp.

It's work for me , check it out:

import * as React from "react"
import {useRef, useEffect, useState} from "react";
import {Container, CanvasBox} from "./style"


const MainView = () => {
    let canvasRef = useRef(null)

    useEffect(() => {
        const canvas = canvasRef.current;
        const context = canvas.getContext('2d');
        let ballRadius = 2;
        var xtemp = canvas.width / 2;
        var ytemp = canvas.height - 30;

        let dx = 2;
        let dy = -2;

        function drawBall() {
            context.beginPath();
            context.arc(xtemp, ytemp, ballRadius, 0, Math.PI * 2);
            context.fillStyle = "white";
            context.fill();
            context.closePath();
        }

        function draw() {
            context.clearRect(0, 0, canvas.width, canvas.height);
            drawBall();

            if (xtemp + dx > canvas.width - ballRadius || xtemp + dx < ballRadius) {
                dx = -dx;
            }
            if (ytemp + dy > canvas.height - ballRadius || ytemp + dy < ballRadius) {
                dy = -dy;
            }
 
            xtemp = xtemp + dx
            ytemp = ytemp + dy;
        }

        setInterval(draw, 10);
    }, [])


    return (
        <>
            <Container>
                <CanvasBox ref={canvasRef}></CanvasBox>
            </Container>
        </>
    )
}

export default MainView
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