Skip to content

Instantly share code, notes, and snippets.

@luizbills
Created September 7, 2024 17:01
Show Gist options
  • Save luizbills/0a16080e105ff19ee7488876ff40d2b8 to your computer and use it in GitHub Desktop.
Save luizbills/0a16080e105ff19ee7488876ff40d2b8 to your computer and use it in GitHub Desktop.
How to create a tiled background image in litecanvas
let bg, tile
litecanvas()
function init() {
loadImage('https://placehold.co/128', (res) => {
tile = res
bg = paint(WIDTH, HEIGHT, () => {
// cache the tiled image
tiled(0, 0, WIDTH, HEIGHT, tile)
})
})
x = y = 0
}
// optional: resize and cache again the tiled image
function resized() {
if (!bg) return
bg = paint(WIDTH, HEIGHT, () => {
// cache the tiled image
tiled(0, 0, WIDTH, HEIGHT, tile)
})
}
function draw() {
if (LOADING) return;
image(x, y, bg)
}
function tiled(x, y, width, height, image) {
const _ctx = ctx(),
pattern = _ctx.createPattern(image, "repeat");
pattern.setTransform(new DOMMatrix([1,0,0,1,x, y]));
_ctx.fillStyle = pattern;
_ctx.fillRect(x, y, width, height);
}