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.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With