Last active
October 10, 2023 02:53
-
-
Save xeecos/9ef8b0d76965587b2170fb36002229c7 to your computer and use it in GitHub Desktop.
render svg using nanosvg.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import {parse as parseSVG} from "./nanosvg.js" | |
let svg = fs.readFileSync(svg_url).toString(); | |
let res = parseSVG(svg,"mm",72); | |
let canvas = document.getElementById("canvas"); | |
let ctx = canvas.getContext("2d"); | |
for (let shape = shapes; shape != null; shape = shape.next) { | |
if(shape.fill.type==1) | |
{ | |
let color = shape.fill.color; | |
let r = Number(color&0xff); | |
let g = Number((color>>8)&0xff); | |
let b = Number((color>>16)&0xff); | |
let alpha = Number((color>>24)&0xff); | |
ctx.fillStyle=`rgba(${r},${g},${b},${alpha/255})`; | |
} | |
if(shape.stroke.type==1) | |
{ | |
let color = shape.stroke.color; | |
let r = Number(color&0xff); | |
let g = Number((color>>8)&0xff); | |
let b = Number((color>>16)&0xff); | |
let alpha = Number((color>>24)&0xff); | |
ctx.strokeStyle=`rgba(${r},${g},${b},${alpha/255})`; | |
} | |
ctx.beginPath(); | |
for (let path = shape.paths; path != null; path = path.next) { | |
drawPath(ctx, path.pts, path.npts, path.closed); | |
} | |
if(shape.stroke.type==1) | |
{ | |
ctx.stroke(); | |
} | |
if(shape.fill.type==1) | |
{ | |
ctx.fill(shape.fillRule==0?"nonzero":"evenodd"); | |
} | |
} | |
function drawPath(ctx, pts, npts, closed) { | |
let i; | |
ctx.moveTo(pts[0], pts[1]); | |
for (i = 0; i < npts - 1; i += 3) { | |
ctx.bezierCurveTo(pts[i * 2 + 2], | |
pts[i * 2 + 3], | |
pts[i * 2 + 4], | |
pts[i * 2 + 5], | |
pts[i * 2 + 6], | |
pts[i * 2 + 7]); | |
} | |
if (closed) { | |
ctx.lineTo(pts[0], pts[1]); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment