Last active
December 8, 2023 14:16
-
-
Save yiwenl/0039903d2a6152acc0c01ea8c5a4761a to your computer and use it in GitHub Desktop.
Sorting characters with number of transparent pixels
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
// Create a canvas element | |
const canvas = document.createElement('canvas'); | |
const context = canvas.getContext('2d'); | |
canvas.width = 64; | |
canvas.height = 64; | |
// Function to calculate non-transparent pixels | |
function countNonTransparentPixels(character) { | |
// Clear the canvas | |
context.clearRect(0, 0, canvas.width, canvas.height); | |
// Set font size equal to canvas size and align text | |
context.font = '64px Arial'; | |
context.textBaseline = 'top'; | |
context.textAlign = 'left'; | |
// Draw the character | |
context.fillText(character, 0, 0); // Position at top-left corner | |
// Get image data | |
const imageData = context.getImageData(0, 0, canvas.width, canvas.height); | |
// Count non-transparent pixels | |
let count = 0; | |
for (let i = 0; i < imageData.data.length; i += 4) { | |
if (imageData.data[i + 3] !== 0) { // Alpha channel is not transparent | |
count++; | |
} | |
} | |
return count; | |
} | |
// Example array of characters | |
let characters = ['A', 'B', 'C', 'D', 'E']; | |
// Sort characters based on non-transparent pixel count | |
characters.sort((a, b) => { | |
return countNonTransparentPixels(a) - countNonTransparentPixels(b); | |
}); | |
console.log(characters); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment