Skip to content

Commit

Permalink
feat: add svg sprite example
Browse files Browse the repository at this point in the history
  • Loading branch information
yisibl committed Feb 22, 2022
1 parent 9f58a45 commit cdf2ad3
Show file tree
Hide file tree
Showing 4 changed files with 70 additions and 1 deletion.
35 changes: 34 additions & 1 deletion __test__/index.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -202,10 +202,43 @@ test('should render `<use xlink:href>` to an `<svg>` element', async (t) => {
<use id="use3" x="0" y="50%" xlink:href="#svg1" />
</svg>
`
const pngData = render(svg)
const resvg = new Resvg(svg, {
fitTo: {
mode: 'height',
value: 800,
},
})
const pngData = resvg.render()
const result = await jimp.read(pngData)

t.is(result.hasAlpha(), false)
t.is(result.getWidth(), 800)
t.is(result.getHeight(), 800)
})

test('should render `<use xlink:href>` to an `<defs>` element', async (t) => {
const svg = `<svg viewBox="0 0 300 300" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
<defs>
<svg id="svg1">
<rect width="50%" height="50%" fill="green" />
</svg>
</defs>
<use id="use1" x="0" y="0" xlink:href="#svg1" />
<use id="use2" x="50%" y="50%" xlink:href="#svg1" />
</svg>`

const resvg = new Resvg(svg, {
fitTo: {
mode: 'width',
value: 900,
},
})
const pngData = resvg.render()
const result = await jimp.read(pngData)

t.is(result.hasAlpha(), true)
t.is(result.getWidth(), 900)
t.is(result.getHeight(), 900)
})

test('should throw because invalid SVG attribute (width attribute is 0)', (t) => {
Expand Down
Binary file added example/sprite-out.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
27 changes: 27 additions & 0 deletions example/sprite.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
const { promises } = require('fs')
const { join } = require('path')
const { performance } = require('perf_hooks')

const { Resvg } = require('../index')

async function main() {
const svg = await promises.readFile(join(__dirname, './sprite.svg'))
const opts = {
fitTo: {
mode: 'width',
value: 500,
},
logLevel: 'debug',
}

const t = performance.now()
const resvg = new Resvg(svg, opts)
const pngData = resvg.render()

console.info('SVG original size:', `${resvg.width} x ${resvg.height}px`)
console.info('✨ Done in', performance.now() - t, 'ms')

await promises.writeFile(join(__dirname, './sprite-out.png'), pngData)
}

main()
9 changes: 9 additions & 0 deletions example/sprite.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.

0 comments on commit cdf2ad3

Please sign in to comment.