Reworked createCrest to load all layers at once

This commit is contained in:
Carlo Morgenstern 2021-10-24 19:08:31 +02:00
parent aa036b169e
commit a677d723cb

View file

@ -203,39 +203,35 @@ class CardCreator {
]); ]);
} }
async createCrest(crestAry) { async createCrest(crests) {
if (!Array.isArray(crests) || crests.length == 0) return null;
const canvas = createCanvas(128, 128); const canvas = createCanvas(128, 128);
const ctx = canvas.getContext('2d'); const ctx = canvas.getContext('2d');
if (crestAry.length == 0) const crestLayers = await Promise.all(crests.map(crest => loadImage(crest)));
return null;
for (let i = 0; i < crestAry.length; i++) { for (const layer of crestLayers) {
const crestLayer = await loadImage(crestAry[i]); ctx.drawImage(layer, 0, 0, 128, 128);
ctx.drawImage(crestLayer, 0, 0, 128, 128);
} }
const imgd = ctx.getImageData(0, 0, 128, 128), const imageData = ctx.getImageData(0, 0, 128, 128);
pix = imgd.data, const pixelData = imageData.data;
newColor = { r: 0, g: 0, b: 0, a: 0 };
for (let i = 0, n = pix.length; i < n; i += 4) { // Iterate over all pixels, where one consists of 4 numbers: r, g, b and a
const r = pix[i], for (let index = 0; index < pixelData.length; index += 4) {
g = pix[i + 1], const [r, g, b] = pixelData.slice(index, index + 3);
b = pix[i + 2];
// If its white then change it // If the pixel is a special grey, change it to be transparent (a = 0)
if (r == 64 && g == 64 && b == 64) { if (r == 64 && g == 64 && b == 64) {
// Change the white to whatever. pixelData[index] = 0;
pix[i] = newColor.r; pixelData[index + 1] = 0;
pix[i + 1] = newColor.g; pixelData[index + 2] = 0;
pix[i + 2] = newColor.b; pixelData[index + 3] = 0;
pix[i + 3] = newColor.a;
} }
} }
ctx.putImageData(imgd, 0, 0); ctx.putImageData(imageData, 0, 0);
return canvas; return canvas;
} }