How to open a canvas as an image in a new tab with Reactjs

6.4k Views Asked by At

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.

3

There are 3 best solutions below

1
On BEST ANSWER

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>

0
On

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>');
}
0
On

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')));
}