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

267
Vistas
How do I animate shapes in canvas, on click, using a redux workflow

Im trying to animate a circle from point a to point b on a hex map. Im using redux to handle the game state. I can get the shape to move on the hex map but I cant get the shape to animate to the end location, it just simply re renders on top the hex I clicked. Heres the main render code:

const root = document.getElementById("game")
const ctx = root.getContext("2d")

store.dispatch(generateMap(6))

render()
function render() {
    cleanup()
    const state = store.getState()

    Map(ctx, state.game.map)
    Player(ctx, state.game.player.location) // a circle shape
    requestAnimationFrame(render) // 
}
store.subscribe(render)
window.addEventListener('resize', render)

root.addEventListener('click', event => {
    const {x, y} = getMousePos(ctx, event)
    store.dispatch(movePlayer(point(x, y)))
})

function cleanup() {
    root.width = window.innerWidth
    root.height = window.innerHeight
    ctx.translate(root.width * 0.5, root.height * 0.5)
    ctx.clearRect(0, 0, root.width, root.height)
}

Every time the player clicks on the canvas I get the nearest hexagons center and set the players location in state. When this happens, the redux store triggers a re render of the canvas.

Im setting the players location with this reducer function:

movePlayer: (state, action) => {
    const map = state.map
    const start = state.player.location
    const end = action.payload

    state.player.location = selectNearestHex(map, point(x, y)).center
}

Player and Map are the canvas shapes:

Map:

const {corners, isTraversable} = hex
ctx.moveTo(0, 0)
ctx.beginPath();
corners.forEach(corner => {
    ctx.lineTo(corner.x, corner.y)
})
ctx.lineTo(corners[0].x, corners[0].y)

ctx.lineWidth = 2
ctx.strokeStyle = '#3f3f3f'
ctx.stroke()

ctx.fillStyle = 'rgba(42, 160, 216, 0)'
if (isTraversable)
    ctx.fillStyle = hex.color
ctx.fill()
ctx.closePath()

Player

ctx.beginPath()
ctx.arc(x, y, radius, 0, 2 * Math.PI, false)
ctx.moveTo(x, y)
if (fill) {
    ctx.fillStyle = fill
    ctx.fill()
}
if (stroke) {
    ctx.lineWidth = strokeWidth
    ctx.strokeStyle = stroke
    ctx.stroke()
}

Thanks in advance for any help!

about 4 years ago · Juan Pablo Isaza
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