【问题标题】:How to open a canvas as an image in a new tab with Reactjs如何使用 Reactjs 在新选项卡中将画布作为图像打开
【发布时间】:2019-03-05 10:18:17
【问题描述】:

我目前有一个由 JsBarcode 的 react 实现生成的画布条形码,称为 react-barcode。 目前,我可以右键单击画布并将其作为图像在新选项卡中打开。如何通过单击按钮来实现此功能?

我已经检查了这个问题的几个答案,但他们都使用 jquery。我正在寻找使用 React 或纯 js 的实现。

【问题讨论】:

  • 将你的画布转换为dataUri(基本上是base64编码的图像) which is of the format data:image/png;base64,iVB..... Then call the js method to open a new tab window.open(url, '_blank')。这里您的url 将是base64 编码图像
  • 那个条形码库创建了一个 SVG,所以不需要画布:codesandbox.io/s/ql92vpqqjw

标签: javascript reactjs jsbarcode


【解决方案1】:

使用HTMLCanvasElement#toDataURL

HTMLCanvasElement.toDataURL() 方法返回一个数据 URI,其中包含由 type 参数指定的格式的图像表示(默认为 PNG)。返回的图像分辨率为 96 dpi。

我认为 SO 会阻止 window.open,但只需复制控制台记录的数据并将其粘贴到新选项卡中即可。

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>

【讨论】:

  • 感谢您的回答。包括@ChrisG 给出的一些sn-ps。
【解决方案2】:

如果图像数据大于 git 允许的最大值,请使用以下代码显示它

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

【讨论】:

    猜你喜欢
    • 2021-08-27
    • 2021-12-29
    • 1970-01-01
    • 2015-03-04
    • 1970-01-01
    • 1970-01-01
    • 2014-01-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多