Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 347
Muljayan Avatar asked Mar 05 '19 10:03

Muljayan


1 Answers

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>
like image 155
kemicofa ghost Avatar answered Oct 02 '22 13:10

kemicofa ghost