title
A prototype
Canvas letters
body{ font-size:20px; font-family:free serif; }
let d = document let b = d.body let paragraph = d.querySelector('p') let content = paragraph.innerHTML let letters = content.split(""); paragraph.innerHTML = "" letters.forEach((letter, index) => { let can = d.createElement('canvas') let ctx = can.getContext('2d') ctx.font = "20px free serif"; ctx.fillStyle = "#ff0000"; ctx.fillText(letter,100,140); trimCanvas(ctx) let span = d.createElement('span') span.innerHTML = letter span.appendChild(can) paragraph.appendChild(span) }); // ctx is the 2d context of the canvas to be trimmed // This function will return false if the canvas contains no or no non transparent pixels. // Returns true if the canvas contains non transparent pixels function trimCanvas(ctx) { // removes transparent edges var x, y, w, h, top, left, right, bottom, data, idx1, idx2, found, imgData; w = ctx.canvas.width; h = ctx.canvas.height; if (!w && !h) { return false } imgData = ctx.getImageData(0, 0, w, h); data = new Uint32Array(imgData.data.buffer); idx1 = 0; idx2 = w * h - 1; found = false; // search from top and bottom to find first rows containing a non transparent pixel. for (y = 0; y < h && !found; y += 1) { for (x = 0; x < w; x += 1) { if (data[idx1++] && !top) { top = y + 1; if (bottom) { // top and bottom found then stop the search found = true; break; } } if (data[idx2--] && !bottom) { bottom = h - y - 1; if (top) { // top and bottom found then stop the search found = true; break; } } } if (y > h - y && !top && !bottom) { return false } // image is completely blank so do nothing } top -= 1; // correct top found = false; // search from left and right to find first column containing a non transparent pixel. for (x = 0; x < w && !found; x += 1) { idx1 = top * w + x; idx2 = top * w + (w - x - 1); for (y = top; y <= bottom; y += 1) { if (data[idx1] && !left) { left = x + 1; if (right) { // if left and right found then stop the search found = true; break; } } if (data[idx2] && !right) { right = w - x - 1; if (left) { // if left and right found then stop the search found = true; break; } } idx1 += w; idx2 += w; } } left -= 1; // correct left if(w === right - left + 1 && h === bottom - top + 1) { return true } // no need to crop if no change in size w = right - left + 1; h = bottom - top + 1; ctx.canvas.width = w; ctx.canvas.height = h; ctx.putImageData(imgData, -left, -top); return true; }
snap
save
new
fork
download
html
css
js
output
gallery
config
➚ link to output
➚ snap player
font size
live reload
snap mode
layout
⤷ switch
★ info and code