UNPKG

svg-path-sdf

Version:

Get signed distance field for a svg path

90 lines (74 loc) 2.24 kB
<!DOCTYPE html> <html> <head> <title>svg-path-sdf demo</title> <style> body { margin: 0; background: black; } canvas { display: block; float: left; } .shape-container { display: inline-block; text-align: center; } .shape-label { margin: 2px 0; } </style> </head> <body> <script type="module"> import sdf from './svg-path-sdf.min.js' import shapes from './shapes.js' // Modified showPath to include labels and container function showPath(path, name) { const cnv = document.createElement('canvas'); const ctx = cnv.getContext('2d'); const w = cnv.width = 77; const h = cnv.height = 77; ctx.fillStyle = 'black'; ctx.fillRect(0, 0, w, h); ctx.fillStyle = 'rgb(0,100,100)'; ctx.strokeStyle = 'white'; ctx.lineWidth = 2; ctx.translate(w / 2, h / 2); if (window.Path2D) { const path2d = new Path2D(path); ctx.stroke(path2d); } ctx.setTransform(1, 0, 0, 1, 0, 0); cnv.title = name document.body.appendChild(cnv); } function showSdf(path, name) { let arr = sdf(path, {w: 77, h: 77, viewBox: [-10, -10, 10, 10], stroke: -2}) let dim = Math.sqrt(arr.length) let cnv = document.body.appendChild(document.createElement('canvas')) let ctx = cnv.getContext('2d') let w = cnv.width = dim let h = cnv.height = dim let iData = ctx.createImageData(w, h) //new ImageData(w, h) let data = iData.data for (let i = 0; i < w; i++) { for (let j = 0; j < h; j++) { data[i*w*4 + j*4 + 0] = arr[i*w + j] * 255 data[i*w*4 + j*4 + 1] = arr[i*w + j] * 255 data[i*w*4 + j*4 + 2] = arr[i*w + j] * 255 data[i*w*4 + j*4 + 3] = 255 } } ctx.putImageData(iData, 0, 0) } // Render all shapes Object.keys(shapes).forEach(name => { const path = shapes[name](10) + shapes.circle(1); showPath(path, name); showSdf(path, name); }); </script> </body> </html>