diff --git a/commands/pokedex/pokedex-box-sprite.js b/commands/pokedex/pokedex-box-sprite.js index 7c12388b..322023ae 100644 --- a/commands/pokedex/pokedex-box-sprite.js +++ b/commands/pokedex/pokedex-box-sprite.js @@ -1,4 +1,6 @@ const Command = require('../../framework/Command'); +const { createCanvas } = require('canvas'); +const { cropToContent } = require('../../util/Canvas'); module.exports = class PokedexBoxSpriteCommand extends Command { constructor(client) { @@ -65,9 +67,17 @@ module.exports = class PokedexBoxSpriteCommand extends Command { async run(msg, { pokemon }) { try { + if (!this.client.pokemon.sprites) await this.client.pokemon.loadSprites(); + const canvas = createCanvas(250, 250); + const ctx = canvas.getContext('2d'); + const x = 40 * (this.id % 12); + const y = Math.floor(this.id / 12) * 30; + ctx.imageSmoothingEnabled = false; + ctx.drawImage(this.store.sprites, x, y, 40, 30, 0, 0, 250, 250); + cropToContent(ctx, canvas.width, canvas.height); return msg.say(`#${pokemon.displayID} - ${pokemon.name}`, { files: [{ - attachment: await pokemon.generateBoxImage(), + attachment: canvas.toBuffer(), name: 'box.png' }] }); diff --git a/structures/pokemon/Pokemon.js b/structures/pokemon/Pokemon.js index a0a4d6e2..ea945a17 100644 --- a/structures/pokemon/Pokemon.js +++ b/structures/pokemon/Pokemon.js @@ -2,6 +2,7 @@ const request = require('node-superfetch'); const { createCanvas } = require('canvas'); const path = require('path'); const { removeDuplicates, firstUpperCase, delay } = require('../../util/Util'); +const { cropToContent } = require('../../util/Canvas'); const missingno = require('../../assets/json/missingno'); const versions = require('../../assets/json/pokedex-location'); @@ -157,6 +158,7 @@ module.exports = class Pokemon { const x = 40 * (this.id % 12); const y = Math.floor(this.id / 12) * 30; ctx.drawImage(this.store.sprites, x, y, 40, 30, 0, 0, 40, 30); + cropToContent(ctx, canvas.width, canvas.height); return canvas.toBuffer(); } diff --git a/util/Canvas.js b/util/Canvas.js index c29b2ec9..83a18494 100644 --- a/util/Canvas.js +++ b/util/Canvas.js @@ -146,6 +146,31 @@ module.exports = class CanvasUtil { return ctx; } + static cropToContent(ctx, w, h) { + const pix = { x: [], y: [] }; + const imageData = ctx.getImageData(0, 0, ctx.canvas.width, ctx.canvas.height); + let index; + for (let y = 0; y < h; y++) { + for (let x = 0; x < w; x++) { + index = ((y * w) + x) * 4; + if (imageData.data[index + 3] > 0) { + pix.x.push(x); + pix.y.push(y); + } + } + } + pix.x.sort((a, b) => a - b); + pix.y.sort((a, b) => a - b); + const n = pix.x.length - 1; + const newW = (1 + pix.x[n]) - pix.x[0]; + const newH = (1 + pix.y[n]) - pix.y[0]; + const cut = ctx.getImageData(pix.x[0], pix.y[0], newW, newH); + ctx.canvas.width = newW; + ctx.canvas.height = newH; + ctx.putImageData(cut, 0, 0); + return ctx; + } + static hasAlpha(image) { const canvas = createCanvas(image.width, image.height); const ctx = canvas.getContext('2d');