将API绘制到HTML画布的数据加载到p5js中

问题描述 投票:0回答:2

我有一个项目,其中有两个画布需要组合,一个在 p5 内部,一个在外部。第一个是 p5js 草图(通过

createCanvas
创建,本质上是一个绘图应用程序),第二个是通过对地图服务的 API 调用自动创建的(我们的用例基本上是注释地图)。

仅供参考,API 查找具有特定 ID 的

div
,然后附加新的
canvas
元素。

我们想要做的是将两个图像拼接在一起成为用户可保存的图像。底层将来自地图 API 画布,顶层将是用户绘制的注释。

我们面临的问题是自动创建的画布作为

webgl
上下文进入,因此我们似乎无法使用任何基本方法在 2d 上下文中获取画布数据。

是否有一种我忽略的easy方法可以做到这一点,或者我是否需要开始弄清楚如何将webgl数据解析为图形对象的

pixels
数组?

下图是我们目前所拥有的 - 绘图正常,地图加载正常,现在我们只需要将它们保存为完整图像以供用户使用。

javascript image-processing html5-canvas webgl p5.js
2个回答
0
投票

将不同画布和不同上下文的内容组合起来确实有点棘手,特别是当其中一个画布使用 WebGL 上下文时。由于 p5.js 对直接使用 WebGL 上下文提供的支持有限,就像使用 2D 上下文一样,因此您需要找到一种替代方法。

html2canvas
库是一个东西,它允许您捕获 HTML 元素(包括画布)的内容并将它们转换为图像。这样,您就可以捕获两个画布(p5.js 和地图 API 画布),将它们组合成单个图像,并将其作为下载链接提供给用户。

  1. 将 html2canvas 库添加到您的项目中。

    <script src="https://html2canvas.hertzen.com/dist/html2canvas.min.js"></script>

    (确保 p5.js 画布和地图 API 画布均已加载并在页面上可见。)

  2. 在按钮的事件处理函数中,您可以使用 html2canvas 库捕获两个画布,然后将它们组合成单个图像。完成后,您可以提供组合图像作为下载链接或执行您想要的任何其他操作。

事件处理函数的示例:

// Event handler function for the button to save the combined image
function saveCombinedImage() {
  // Get references to the p5.js canvas and the map API canvas
  const p5Canvas = document.getElementById('your-p5-canvas-id');
  const mapApiCanvas = document.getElementById('your-map-api-canvas-id');

  // Use html2canvas to capture both canvases
  html2canvas(p5Canvas).then((p5CanvasCapture) => {
    html2canvas(mapApiCanvas).then((mapApiCanvasCapture) => {
      // Create a new canvas to combine the captured canvases
      const combinedCanvas = document.createElement('canvas');
      combinedCanvas.width = p5CanvasCapture.width;
      combinedCanvas.height = p5CanvasCapture.height;
      const ctx = combinedCanvas.getContext('2d');

      // Draw the map API canvas as the bottom layer
      ctx.drawImage(mapApiCanvasCapture, 0, 0);

      // Draw the p5.js canvas as the top layer
      ctx.drawImage(p5CanvasCapture, 0, 0);

      // Now the `combinedCanvas` contains the merged image of both canvases
      // You can offer this as a download link or use it as needed.

      // For example, create a link for the user to download the image
      const downloadLink = document.createElement('a');
      downloadLink.href = combinedCanvas.toDataURL();
      downloadLink.download = 'combined_image.png';
      downloadLink.click();
    });
  });
}

在此示例中,将

your-p5-canvas-id
your-map-api-canvas-id
分别替换为 p5.js 画布和地图 API 画布的实际 ID。


0
投票

“我需要弄清楚如何将 webgl 数据解析为图形对象的像素数组”

这是初步答案。将尽快更新工作示例(2D/3D 混合)

有一个选项可以使用以下方式捕获任何 webGL 画布的内容(例如: P5.js 内容):

https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/readPixels

© www.soinside.com 2019 - 2024. All rights reserved.