簡體   English   中英

在 png/jpg 圖像中捕獲 html div 的內容

[英]Capturing the content of a html div in a png/jpg image

我正在嘗試使用 html 和 javascript 制作一個非常簡單的人臉圖像生成器,用戶可以在其中選中一些復選框並向其中添加部分人臉。 復選框在一個表單中,我希望用戶能夠在點擊提交按鈕時下載他們創建的 png/jpg 圖像。 (或者讓它自動下載,沒關系)。 我嘗試搜索它,但除了我不允許使用的 html2canvas 之外,我真的找不到任何東西。

這是 html 代碼(最小可復制版本):

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body id="pageBody">

  <form action="" id="form">
    <label for="body">Body</label><input type="checkbox" name="body" id="body">
    <label for="eyes">Eyes</label><input type="checkbox" name="eyes" id="eyes">
    <label for="nose">Nose</label><input type="checkbox" name="nose" id="nose">
    <label for="mouth">Mouth</label><input type="checkbox" name="mouth" id="mouth">
    <label for="hat">Hat</label><input type="checkbox" name="hat" id="hat">
    <input type="submit" value="submit">
  </form>
  <br>
  <div id="pic">
    <img id="bodyImg" src="imgs/body.png"/>
    <img id="eyesImg" src="imgs/eyes.png"/>
    <img id="mouthImg" src="imgs/mouth.png"/>
    <img id="noseImg" src="imgs/nose.png"/>
    <img id="hatImg" src="imgs/hat.png"/>
  </div>
  
  
</body>
</html>

有什么建議么?

好的,您可能不需要 SVG 部分,如果您只是想將圖像放在一起然后允許用戶保存,那么您只需要將圖像到 Canvas,然后保存 ZFCC790C72A86190DE51B549D0DDDC6。

我在這里創建了一個小提琴,它基本上加載了 4 張圖像,然后將它們並排放置在 canvas 上,然后您就可以下載了。 不幸的是,不能使用 SO 片段,因為它太沙盒了,無法正常工作,但 fiddle 可以正常工作。

const svg = document.querySelector('svg');
const canvas = document.querySelector('canvas');
const button = document.querySelector('button');
const ctx = canvas.getContext("2d");

function loadImg(src) {
  return new Promise((resolve, reject) => {
    const i = new Image();
    i.setAttribute('crossOrigin', 'anonymous');
    i.src = src;
    i.onload = () => resolve(i);
    i.onerror = (e) => reject(e);
  });
}

async function doIt() {
  const [i1, i2, i3, i4] = await Promise.all([
    loadImg("https://picsum.photos/id/237/100/150"),
    loadImg("https://picsum.photos/id/238/100/150"),
    loadImg("https://picsum.photos/id/239/100/150"),
    loadImg("https://picsum.photos/id/240/100/150")
  ]);
  ctx.drawImage(i1, 0, 0);
  ctx.drawImage(i2, 100, 0);
  ctx.drawImage(i3, 0, 150);
  ctx.drawImage(i4, 100, 150);
}

function save() {
  const i = canvas.toDataURL("image/png")
    .replace("image/png", "image/octet-stream");
  location.href = i;
}


doIt();
button.addEventListener('click', save)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM