6

I currently have a canvas barcode generated by the react implementation of JsBarcode called react-barcode. Currently, I am able to right-click the canvas and open it as an image in a new tab. How do I implement this functionality with a click of a button instead?

I have already checked several answers to this problem but all of them use jquery. I am looking for implementation with React or pure js.

Muljayan
  • 3,588
  • 10
  • 30
  • 54
  • Convert your canvas to `dataUri`(basically base64 encodede image`) which is of the format `data:image/png;base64,iVB....`. Then call the js method to open a new tab `window.open(url, '_blank'). Here your `url` will be the `base64` encoded imagee – Panther Mar 05 '19 at 10:23
  • That barcode library creates an SVG, so no need for a canvas: https://codesandbox.io/s/ql92vpqqjw –  Mar 05 '19 at 10:56

3 Answers3

7

Use HTMLCanvasElement#toDataURL

The HTMLCanvasElement.toDataURL() method returns a data URI containing a representation of the image in the format specified by the type parameter (defaults to PNG). The returned image is in a resolution of 96 dpi.

I think that SO blocks window.open, but simply copy the console logged data and paste it in a new tab.

const canvas = document.getElementById("canvas");
const button = document.getElementById("click");

const context = canvas.getContext("2d");
context.fillStyle = "#FF0000";
context.fillRect(20, 20, 150, 100);

button.addEventListener("click", function(){
  const dataUrl = canvas.toDataURL("png");
  console.log(dataUrl);
  const win = window.open(dataUrl, '_blank');
});
<canvas id="canvas" width="100" height="100"></canvas>
<button id="click">Click</button>
kemicofa ghost
  • 16,349
  • 8
  • 82
  • 131
3

Dynamically opening data: URLs in Chrome doesn't work any more starting from Chrome 60 (deprecated in Chrome 58).

Instead, you can use and open canvas blobs converted to object URLs:

function openImage(canvas) {
    canvas.toBlob((blob) => window.open(URL.createObjectURL(blob), '_blank')));
}
zorian
  • 31
  • 1
0

If the image data is larger than the maximum allowed for git use the following code to display it

function openImage(base64URL){
    var win = window.open();
    win.document.write('<iframe src="' + base64URL  + '" frameborder="0" style="border:0; 
   top:0px; left:0px; bottom:0px; right:0px; width:100%; height:100%;" allowfullscreen> 
   </iframe>');
}
M.Ali El-Sayed
  • 1,608
  • 20
  • 23