ushelp / EasyQRCodeJS

EasyQRCodeJS is a flexible QR code generator using JavaScript, supporting various drawing methods (Canvas, SVG, Table) and customization options. It's compatible with major frameworks and can be directly downloaded in the browser.
https://easyproject.cn/easyqrcode
MIT License
742 stars 155 forks source link

Add `viewBox` attribute to root SVG element #92

Open Gazook89 opened 3 months ago

Gazook89 commented 3 months ago

Right now it doesn't seem like there is any way to set a viewBox for the SVG render, so it makes it difficult to resize the SVG with CSS. Possibly this is my shortcoming with CSS, but I do know that it's at least a little easier if there is a viewBox on the SVG.

I added a line to the script, right in the part that defines the root svg element, shown below:

https://github.com/ushelp/EasyQRCodeJS/blob/e513316fe390c3c29bb06ab9ff0dbff25f9be0c4/src/canvas2svg.js#L253-L258

this.__root.setAttribute("viewBox",`0 0 ${this.width} ${this.height}`)

And it works for me to now use CSS like this to set width/height and get proper scaling (without setting an absolute px value):

.qr {                               // container
    width: 50%;
    max-width: 100px;
    & svg {
        width: 100%;
        height: 100%;
    }
}
graymatter00 commented 3 months ago

@Gazook89 I had the same/similar issue. My solution...

Use the EncodeText method to create the QrCode object.

Then use the ToGraphicsPath method to get the SVG path of the QR Code. => PATH

Then use the Size property to get the size of the QR code. => SIZE

Then, in HTML, build the svg element, placing the SIZE in the 3rd and 4th parameter of the viewBox attribute, and the PATH in a d attribute of an svg path element.

Gazook89 commented 3 months ago

@graymatter00 oh I just edited the script directly as indicated above and it works. I just set the viewBox attribute to “0 0 width height”.

graymatter00 commented 3 months ago

Sorry @Gazook89. Please ignore my comment. I thought this was a different QR Code project and was referring to that project. I forgot that I was also Watching this project. My mistake. I must get more sleep. 🙄