Make a game with pixels functionally

Kyle Perik 4d2178e8de fix readme another time 3 months ago
README.MD 4d2178e8de fix readme another time 3 months ago
example.gif 85949c00bb add example gif 11 months ago
index.html 21ecac539a refactoring 3 months ago
main.js 21ecac539a refactoring 3 months ago
pixelcanvas.js 21ecac539a refactoring 3 months ago

README.MD

Pixel Canvas

example

Try it

git clone https://git.kyleperik.com/kyle/pixelcanvas
cd pixelcanvas
python -m http.server # or otherwise navigate to the files on your browser

Usage

Make a PixelCanvas object

const canvas = document.getElementById('canvas');
const pixelSize = 10;
const initialState = { x: 10, y: 10 };
const pc = getPixelCanvas(canvas, pixelSize, initialState);

Draw a rectangle

// x, y, width, height, color
pc.rect(10, 10, 2, 2, 'blue');

Start a game loop

const intervalMilliseconds = 100;
pc.gameLoop(intervalMilliseconds, last => {
    // draw with rect
    const size = pc.screenSize();
    pc.rect(0, 0, size.x, size.y, '#222');
    pc.rect(last.x, last.y, 2, 2, 'white');
    // return new state
    const newState = {
        ...last,
        x: last.x + 1,
        y: last.y + 1,
    };
    return newState;
});

Add event listener

Note: Make sure you add tabindex="1" on your canvas to allow focus

pc.listen('keydown', (last, e) => {
    // return new state
    return { x: 0, y: 0 };
});