Created
September 7, 2024 17:01
-
-
Save luizbills/0a16080e105ff19ee7488876ff40d2b8 to your computer and use it in GitHub Desktop.
How to create a tiled background image in litecanvas
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Demo:
https://litecanvas.js.org?c=eJyNUl1LwzAUfc%2BvuO7FFMK6%2BSSTCcJkG6gTHfggIlmatYEsLemd25T9d2%2FSKvMDkTYpOTfn3HOSWo2wyAWgsZoxa1Ar6V5kzRPGlmun0JQOjDPIE3hjALaU2XQlc82PC8SqHqRpZaXSRWmzrirT%2FsnpsQDudZ3A8DxSIIrDEAiMy0VOi0oah%2FxhOppPBEwup%2BPJnHgHJIA0BSVVoQHDII0MTGjdliPCewLo%2FaYTSknctg%2BfOG2p6Y5Gj%2B0ZI%2BmyCtmkHQRf5lWDdFnbT%2BZk7kfXz%2BNo9mftiZgl8KNFnhCMa%2B%2FYf%2FP9me4f2SjU%2FuCOMi83B46uZhej6c34w9VZgOO1bQXsBFn8ym76NbWNybAQUGiTFygaWiOsSlcjPCsMZ0kzT0R0W0lE7R2BodZVXkvUtw3II19Ax%2BuK4E4SrLSEbq1x7qWrl6Vfcac3MJpdX0v0Zssf%2B6JHT18EU09JpEX1pbH2Hnfxj2p1vtTutMLfkpDCnr0Dcc7f%2BQ%3D%3D
Preview: