UNPKG

transparent-pixel-generator

Version:

A lightweight, dependency-free library to generate transparent pixel PNGs on the client-side, ideal for creating dynamic backgrounds and placeholders without server requests.

2 lines (1 loc) 1.29 kB
(function(i,a){typeof exports=="object"&&typeof module<"u"?a(exports):typeof define=="function"&&define.amd?define(["exports"],a):(i=typeof globalThis<"u"?globalThis:i||self,a(i.transparentPixelGenerator={}))})(this,function(i){"use strict";function a(f){let r=f.startsWith("#")?f.slice(1):f;if(r.length===3&&(r=r.split("").map(o=>o+o).join("")),!/^[a-f\d]{6}$/i.test(r))return null;const e=parseInt(r,16),s=e>>16&255,c=e>>8&255,d=e&255;return{r:s,g:c,b:d}}function g({width:f=1,height:r=1,color:e="#ffffff",alpha:s=0}){let{r:c,g:d,b:o}={r:255,g:255,b:255};const h=typeof s=="number"&&!isNaN(s)?Math.max(0,Math.min(1,s)):s;if(typeof e=="string"&&e.startsWith("#")){const t=a(e);t&&(c=t.r,d=t.g,o=t.b)}else{const t=e.match(/rgb\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)/);if(t)c=parseInt(t[1],10),d=parseInt(t[2],10),o=parseInt(t[3],10);else throw new Error("Invalid color format. Use valid hex or rgb formats.")}const n=document.createElement("canvas");n.width=f,n.height=r;const l=n.getContext("2d");if(!l)throw new Error("Failed to get canvas context");return l.clearRect(0,0,n.width,n.height),l.fillStyle=`rgba(${c}, ${d}, ${o}, ${h})`,l.fillRect(0,0,n.width,n.height),n.toDataURL("image/png")}i.transparentPixelGenerator=g,Object.defineProperty(i,Symbol.toStringTag,{value:"Module"})});