38 lines
1.3 KiB
JavaScript
38 lines
1.3 KiB
JavaScript
import QRCode from 'qrcode'
|
|
|
|
self.onmessage = async (e) => {
|
|
const { id, text, ecc, isBgTransparent, bgColor, fgType, fgColor1, fgColor2 } = e.data
|
|
|
|
if (!text) {
|
|
self.postMessage({ id, svgContent: '' })
|
|
return
|
|
}
|
|
|
|
try {
|
|
let svgContent = await QRCode.toString(text, {
|
|
type: 'svg',
|
|
errorCorrectionLevel: ecc,
|
|
margin: 1,
|
|
color: {
|
|
dark: fgType === 'solid' ? fgColor1 : '#000000',
|
|
light: isBgTransparent ? '#00000000' : bgColor
|
|
}
|
|
})
|
|
|
|
if (fgType !== 'solid') {
|
|
const isLinear = fgType === 'linear'
|
|
const defs = isLinear
|
|
? `<defs><linearGradient id="qr-grad" x1="0%" y1="0%" x2="100%" y2="100%"><stop offset="0%" stop-color="${fgColor1}" /><stop offset="100%" stop-color="${fgColor2}" /></linearGradient></defs>`
|
|
: `<defs><radialGradient id="qr-grad" cx="50%" cy="50%" r="50%"><stop offset="0%" stop-color="${fgColor1}" /><stop offset="100%" stop-color="${fgColor2}" /></radialGradient></defs>`
|
|
|
|
svgContent = svgContent.replace('<svg ', `<svg >${defs}`)
|
|
// qrcode outputs <path stroke="#000000"...> so it's safe to replace
|
|
svgContent = svgContent.replace(/stroke="#000000"/g, 'stroke="url(#qr-grad)"')
|
|
}
|
|
|
|
self.postMessage({ id, svgContent })
|
|
} catch (err) {
|
|
self.postMessage({ id, error: err.message })
|
|
}
|
|
}
|