简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM