feat(qr): add background and foreground colors/gradient customization
This commit is contained in:
@@ -1,7 +1,7 @@
|
||||
import QRCode from 'qrcode'
|
||||
|
||||
self.onmessage = async (e) => {
|
||||
const { id, text, ecc } = e.data
|
||||
const { id, text, ecc, isBgTransparent, bgColor, fgType, fgColor1, fgColor2 } = e.data
|
||||
|
||||
if (!text) {
|
||||
self.postMessage({ id, svgContent: '' })
|
||||
@@ -9,12 +9,27 @@ self.onmessage = async (e) => {
|
||||
}
|
||||
|
||||
try {
|
||||
const svgContent = await QRCode.toString(text, {
|
||||
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 })
|
||||
|
||||
Reference in New Issue
Block a user