puzzle/game/Graphics.js

56 lines
1.4 KiB
JavaScript
Raw Normal View History

2020-11-09 00:29:07 +01:00
function createCanvas(width = 0, height = 0) {
const c = document.createElement('canvas')
2020-11-25 22:03:35 +01:00
c.width = width
c.height = height
2020-11-09 00:29:07 +01:00
return c
}
async function loadImageToBitmap(imagePath) {
2021-04-16 01:52:34 +02:00
return new Promise((resolve) => {
const img = new Image()
img.onload = () => {
createImageBitmap(img).then(resolve)
}
2020-11-09 00:29:07 +01:00
img.src = imagePath
2021-04-16 01:52:34 +02:00
})
2020-11-09 00:29:07 +01:00
}
2020-11-10 18:48:16 +01:00
async function resizeBitmap (bitmap, width, height) {
const c = createCanvas(width, height)
const ctx = c.getContext('2d')
ctx.drawImage(bitmap, 0, 0, bitmap.width, bitmap.height, 0, 0, width, height)
return await createImageBitmap(c)
2020-11-09 00:29:07 +01:00
}
2020-11-10 18:48:16 +01:00
async function createBitmap(width, height, color) {
const c = createCanvas(width, height)
const ctx = c.getContext('2d')
ctx.fillStyle = color
ctx.fillRect(0, 0, width, height)
return await createImageBitmap(c)
2020-11-09 20:30:37 +01:00
}
2020-11-25 22:03:35 +01:00
async function colorize(image, mask, color) {
const c = createCanvas(image.width, image.height)
const ctx = c.getContext('2d')
ctx.save()
ctx.drawImage(mask, 0, 0)
ctx.fillStyle = color
ctx.globalCompositeOperation = "source-in"
ctx.fillRect(0, 0, mask.width, mask.height)
ctx.restore()
ctx.save()
ctx.globalCompositeOperation = "destination-over"
ctx.drawImage(image, 0, 0)
ctx.restore()
return await createImageBitmap(c)
}
2020-11-09 00:29:07 +01:00
export default {
2020-11-10 18:48:16 +01:00
createBitmap,
2020-11-09 00:29:07 +01:00
createCanvas,
loadImageToBitmap,
resizeBitmap,
2020-11-25 22:03:35 +01:00
colorize,
2020-11-09 00:29:07 +01:00
}