svg-image-util.js (2452B)
1 /** 2 * Reusable SVG data uri prefix for generated SVGs. 3 */ 4 const SVG_DATA_URI_PREFIX = 'data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg"'; 5 /** 6 * Reusable SVG data uri suffix for generated SVGs. 7 */ 8 const SVG_DATA_URI_SUFFIX = '><rect fill="brown" x="-2000" y="-2000" width="4000" height="4000"></rect><rect fill="green" height="50" width="50"></rect><rect fill="yellow" x="10" y="10" height="30" width="30"></rect></svg>'; 9 10 /** 11 * Generates full data URI for an SVG document, with the given parameters 12 * on the SVG element. 13 * 14 * @param aWidth The width attribute, or null for no width. 15 * @param aHeight The height attribute, or null for no height. 16 * @param aViewbox The viewBox attribute, or null for no viewBox. 17 */ 18 function generateSVGDataURI(aWidth, aHeight, aViewBox) { 19 let datauri = SVG_DATA_URI_PREFIX; 20 21 if (aWidth) { 22 datauri += " width=\"" + aWidth + "\"" 23 } 24 25 if (aHeight) { 26 datauri += " height=\"" + aHeight + "\""; 27 } 28 29 if (aViewBox) { 30 datauri += " viewBox=\"" + aViewBox + "\""; 31 } 32 33 datauri += SVG_DATA_URI_SUFFIX; 34 35 return datauri; 36 } 37 38 /** 39 * Generates a canvas, with the given width and height parameters, and uses 40 * CanvasRenderingContext2D.drawImage() to draw a SVG image with the given 41 * width and height attributes. 42 * 43 * @param aCanvasWidth The width attribute of the canvas. 44 * @param aCanvasHeight The height attribute of the canvas. 45 * @param aSVGWidth The width attribute of the svg, or null for no width. 46 * @param aSVGHeight The height attribute of the svg, or null for no height. 47 * @param aSVGViewBox The viewBox attribute sf the svg, or null for no viewBox. 48 * 49 * @returns A promise that resolves when the SVG image has been drawn to the 50 * created canvas 51 */ 52 async function generateCanvasDrawImageSVG(aCanvasWidth, aCanvasHeight, aSVGWidth, 53 aSVGHeight, aSVGViewBox) { 54 let canvas = document.createElement("canvas"); 55 let ctx = canvas.getContext("2d"); 56 document.body.appendChild(canvas); 57 58 canvas.setAttribute("width", aCanvasWidth); 59 canvas.setAttribute("height", aCanvasHeight); 60 61 let img = document.createElement("img"); 62 63 let promise = new Promise(resolve => { 64 img.onload = () => { 65 ctx.drawImage(img, 0, 0); 66 resolve(); 67 }; 68 }); 69 70 let uri = generateSVGDataURI(aSVGWidth, aSVGHeight, aSVGViewBox); 71 img.src = uri; 72 73 return promise; 74 }