0

Estoy creando un fondo parallax en canvas con JavaScript con movimiento en x, que contiene varias imágenes de 1920x1080 el cual tiene movimiento de izquierda a derecha y en reversa

Tengo el siguiente código JavaScript:

layer.js

export class Layer {
    constructor({ layer_path, layer_max, layer_height, layer_reverse, layer_speed }) {
        this.layers = []

        for (let i = 0; i < layer_max; i++) {
            let layer_image_count = i <= 9 ? `0${i}` : `${i}`
            let layer_speed_modifier = i < 9 ? `0.0${i + 1}` : `0.${i + 1}`
            let layer_image = new Image()

            layer_image.src = `${layer_path}/layer_${layer_image_count}.png`

            let layer_y = 0
            let layer_x = 0
            let layer_width = layer_image.width
            layer_speed_modifier = layer_reverse ? `-${layer_speed_modifier}` : layer_speed_modifier
            let layer_frame_init = 0

            this.layers.push({
                layer_image,
                layer_x,
                layer_y,
                layer_width,
                layer_height,
                layer_reverse,
                layer_speed_modifier,
                layer_speed,
                layer_frame_init
            })
        }
    }

    update() {
        for (let layer of this.layers) {
            layer.speed = layer.layer_speed * layer.layer_speed_modifier
            layer.layer_x = (layer.layer_frame_init * layer.speed) % layer.layer_width
            layer.layer_frame_init--
        }
    }

    draw({ ctx }) {
        for (let layer of this.layers) {
            ctx.drawImage(layer.layer_image, layer.layer_x, layer.layer_y, layer.layer_width, layer.layer_height)
            ctx.drawImage(layer.layer_image, layer.layer_reverse ? layer.layer_x - layer.layer_width : layer.layer_x + layer.layer_width, layer.layer_y, layer.layer_width, layer.layer_height)
        }
    }
}

main.js

const layer_path = "/assets/img/layer"
const layer_max = 12
const layer_height = canvas_height
const layer_reverse = true
const layer_speed = 50
const layer_1 = new Layer({ layer_path, layer_max, layer_height, layer_reverse, layer_speed })

const animate = async () => {
    ctx.clearRect(0, 0, canvas_width, canvas_height)

    layer_1.update()
    layer_1.draw({ ctx })
    requestAnimationFrame(animate)
}
await animate()

El error es que cuando en layer_reverse coloco true, se muestra una línea vertical en la animación, la cual se mueve lentamente de izquierda a derecha hasta que desaparece y no se muestra más y cuando coloco false todo funciona bien

introducir la descripción de la imagen aquí

Espero puedan ayudarme Bendiciones.

2
  • ¿Pasa con cualquier asset que uses de fondo? Commented el 17 oct. 2023 a las 7:17
  • @PabloLozano Si efectivamente con cualquier cantidad de fondos destinados para un parallax en x Commented el 18 oct. 2023 a las 1:13

1 respuesta 1

1

Conseguí la solución y la dejo para el que pueda necesitarlo, tuve que modificar mucho el código pero así funciona mejor:

index.html

<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Game</title>
    <link rel="stylesheet" href="/assets/main.css" />
    <script defer type="module" src="/assets/js/main.js"></script>
</head>
<body>
    <canvas></canvas>
</body>
</html>

main.css / CSS moderno no es SCSS

* {
    margin: 0;
    padding: 0;
    border: 0;
    outline: 0;
    list-style: none;
    box-sizing: border-box;
    user-select: none;
    -webkit-user-drag: none;

    &::before,
    &::after {
        box-sizing: border-box;
    }
}

body {
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: #222;
    height: 100dvh;
}

canvas {
    background-color: #111;
}

config.json

{
    "layer_states": [
        {
            "image": "/assets/img/layer/layer_00.png",
            "reverse": false,
            "speed": "0.00"
        },
        {
            "image": "/assets/img/layer/layer_01.png",
            "reverse": false,
            "speed": "0.01"
        },
        {
            "image": "/assets/img/layer/layer_02.png",
            "reverse": false,
            "speed": "0.02"
        },
        {
            "image": "/assets/img/layer/layer_03.png",
            "reverse": false,
            "speed": "0.03"
        },
        {
            "image": "/assets/img/layer/layer_04.png",
            "reverse": false,
            "speed": "0.04"
        },
        {
            "image": "/assets/img/layer/layer_05.png",
            "reverse": false,
            "speed": "0.05"
        },
        {
            "image": "/assets/img/layer/layer_06.png",
            "reverse": false,
            "speed": "0.06"
        },
        {
            "image": "/assets/img/layer/layer_07.png",
            "reverse": false,
            "speed": "0.07"
        },
        {
            "image": "/assets/img/layer/layer_08.png",
            "reverse": false,
            "speed": "0.08"
        },
        {
            "image": "/assets/img/layer/layer_09.png",
            "reverse": false,
            "speed": "0.09"
        },
        {
            "image": "/assets/img/layer/layer_10.png",
            "reverse": false,
            "speed": "0.10"
        },
        {
            "image": "/assets/img/layer/layer_11.png",
            "reverse": false,
            "speed": "0.11"
        }
     ],
    "layer_speed": 50
}

init.js

const canvas = document.querySelector("canvas")

export const ctx = canvas.getContext("2d")
export const canvas_width = (canvas_width = 64 * 16)
export const canvas_height = (canvas_height = 64 * 9)

ctx.imageSmoothingEnabled = false

layer.js

export class Layer {
    constructor({ states, height, speed }) {
        this.layers = []

        for (let i = 0; i < states.length; i++) {
            let image = new Image()

            image.src = states[i].image

            let reverse = states[i].reverse
            let y = 0
            let x = 0
            let width = image.width
            let frame_init = 0
            let speed_modifier = states[i].speed

            speed_modifier = reverse ? `-${speed_modifier}` : speed_modifier

            this.layers.push({
                image,
                x,
                y,
                width,
                height,
                reverse,
                speed_modifier,
                speed,
                frame_init
            })
        }
    }

    update() {
        for (let layer of this.layers) {
            layer.frame_speed = layer.speed * layer.speed_modifier
            layer.x = (layer.frame_init * layer.frame_speed) % layer.width
            layer.frame_init--
        }
    }

    draw({ ctx }) {
        for (let layer of this.layers) {
            ctx.drawImage(layer.image, layer.x, layer.y, layer.width, layer.height)
            ctx.drawImage(layer.image, layer.reverse ? layer.x - layer.width : layer.x + layer.width, layer.y, layer.width, layer.height)
        }
    }
}

main.js

import _c from "/config/config.json" assert { type: "json" }
import { ctx, canvas_width, canvas_height } from "/assets/js/modules/init.js"
import { Layer } from "/assets/js/modules/layer.js"

document.addEventListener("DOMContentLoaded", async () => {

    /* LAYER */
    const layer_1 = new Layer({ states: _c.layer_states, height: canvas_height, speed: _c.layer_speed })

    const animate = async () => {
        ctx.clearRect(0, 0, canvas_width, canvas_height)

        /* LAYER */
        layer_1.update()
        layer_1.draw({ ctx })

        requestAnimationFrame(animate)
    }
    await animate()
})

Imágenes: https://digitalmoons.itch.io/parallax-forest-background

Ya no da el error de la línea de un pixelada.

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge you have read our privacy policy.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.