jQuery(document).ready(function($) { // set up a percent to scale var percen = 1; var gridWidth = 160; var gridHeight = 120; gridWidth = gridWidth * percen; gridHeight = gridHeight * percen; // Load text from the file specified by the variable $.get(mytext, function(data) { // Replace line breaks with vertical bars var text = data.replace(/(\r\n|\n|\r)/g, '|'); console.log('text.length: ' + text.length); var totalCharactersUsed = 0; // Dynamically load the image specified by the variable var img = new Image(); img.src = myimage; img.crossOrigin = "Anonymous"; img.onload = function() { var canvas = document.createElement('canvas'); canvas.width = gridWidth; canvas.height = gridHeight; var ctx = canvas.getContext('2d'); ctx.drawImage(img, 0, 0, img.width, img.height, 0, 0, gridWidth, gridHeight); var imageData = ctx.getImageData(0, 0, gridWidth, gridHeight).data; var output = ""; var textIndex = 0; var maxWidth = 1; // Target width in pixels per grid cell // Create a temporary element to measure text width var tempSpan = $('').css({visibility: 'hidden', position: 'absolute', whiteSpace: 'nowrap'}).appendTo('body'); outerLoop: for (var y = 0; y < gridHeight; y++) { var rowOutput = ""; // Store each row's output separately for (var x = 0; x < gridWidth; x++) { var letter; if (repeatText || textIndex < text.length) { var i = (y * gridWidth + x) * 4; var r = imageData[i]; var g = imageData[i + 1]; var b = imageData[i + 2]; var alpha = imageData[i + 3]; var grayscale = (r + g + b) / 3; var invertedGrayscale = 255 - grayscale; // Invert the grayscale value var weightClass = Math.ceil(invertedGrayscale / 28.33); // Corrected calculation weightClass = Math.max(1, Math.min(9, weightClass)); // Ensure it's between 1 and 9 weightClass = 3; if (alpha === 0 || grayscale === 255) { letter = " "; // Use   for white pixels } else { letter = "" + text[textIndex % text.length] + ""; textIndex++; // Increment only if a non-white pixel totalCharactersUsed++; // Count total characters used } } else { letter = " "; // Fill the rest of the row with spaces if text ends } // Append the current letter to the rowOutput rowOutput += letter; // Measure the width of the entire row so far tempSpan.html(rowOutput); var rowWidth = tempSpan.width(); // Break to the next line if the current row exceeds maxWidth if (rowWidth > maxWidth) { break; // Exit the current row and start a new one } } output += "

" + rowOutput + "

\n"; // Wrap each row in a

tag } tempSpan.remove(); // Remove the temporary span $('#typography-output').html(output); // Log the total number of characters actually used console.log('Total characters used: ' + totalCharactersUsed); }; }); });