Search code examples
javascriptcanvasjsbarcode

How to generate an image from the JsBarcode implementation?


I am using JsBarcode to generate one during a person's checkout. I want to send this to their email but I can't since the generated one is a collection of paths inside an SVG so they don't make it to their email (nothing is rendered). So I wanted to make this code, once generated, an image.

My HTML: <svg id="barcode"></svg><canvas id="canvas"></canvas>

I tried to do after generating the barcode (which works):

JsBarcode("#barcode", result.source.number, {
                  text: result.source.number.match(/.{1,4}/g).join ("  "),
                  width: 2,
                  height: 50,
                  fontSize: 15,
                });

To call:

var canvas = $("#barcode");
var img = canvas.toDataURL("image/png");
$("#canvas").append('<img src="' + img + '"/>');

However, when doing that, I get:

canvas.toDataURL is not a function. I Googled around and, from what I can tell, that would make more sense if I were giving toDataURL() an array but there's literally no other canvas in the page. What am I missing here?

At this point, I realize this will show the barcode twice in the code but I don't care, I'll fix that after. I'm more interested in generating the image and I don't seem to be able to do so.


Solution

  • You are using jquery and it wraps the element in an array. You can select the original DOM node with element[0] or with element.get(0) https://api.jquery.com/get/

    You don't need a canvas element, you can serialize the SVG into a base64 URL and use this as the image source.

    var number = '12345678';
    
    JsBarcode("#barcode", number, {
      text: number.match(/.{1,4}/g).join("  "),
      width: 2,
      height: 50,
      fontSize: 15,
    });
    
    var svg = $("#barcode")[0];
    
    var xml = new XMLSerializer().serializeToString(svg);
    
    var base64 = 'data:image/svg+xml;base64,' + btoa(xml);
    
    var img = $("#image")[0];
    
    img.src = base64;
    svg {
      border: 1px solid green;
    }
    
    img {
      border: 1px solid red;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script src="https://cdn.jsdelivr.net/jsbarcode/3.6.0/JsBarcode.all.min.js"></script>
    
    <svg id="barcode"></svg>
    
    <img id="image"></img>