83 lines
3.1 KiB
HTML
83 lines
3.1 KiB
HTML
<!DOCTYPE html>
|
|
<html lang="zh">
|
|
|
|
<head>
|
|
<meta charset="UTF-8">
|
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
|
<title>海报合成</title>
|
|
<script src="https://cdn.jsdelivr.net/npm/qrcodejs/qrcode.min.js"></script>
|
|
</head>
|
|
|
|
<body>
|
|
<img id="resultImage" style="width: 650px;" />
|
|
<script>
|
|
function generatePosterWithQR(backgroundUrl, qrText) {
|
|
return new Promise((resolve, reject) => {
|
|
const canvas = document.createElement("canvas");
|
|
const ctx = canvas.getContext("2d");
|
|
const qrSize = 500; // 二维码大小
|
|
|
|
const poster = new Image();
|
|
poster.crossOrigin = "anonymous"; // 允许跨域加载
|
|
poster.src = backgroundUrl;
|
|
|
|
poster.onload = () => {
|
|
canvas.width = poster.width;
|
|
canvas.height = poster.height;
|
|
ctx.drawImage(poster, 0, 0);
|
|
|
|
// 创建隐藏的 div 生成二维码
|
|
const qrDiv = document.createElement("div");
|
|
qrDiv.style.display = "none";
|
|
document.body.appendChild(qrDiv);
|
|
|
|
const qrCode = new QRCode(qrDiv, {
|
|
text: qrText,
|
|
width: qrSize,
|
|
height: qrSize
|
|
});
|
|
|
|
setTimeout(() => {
|
|
const qrCanvas = qrDiv.querySelector("canvas");
|
|
if (qrCanvas) {
|
|
const qrImg = new Image();
|
|
qrImg.src = qrCanvas.toDataURL("image/png");
|
|
|
|
qrImg.onload = () => {
|
|
const qrX = (canvas.width - qrSize) * 0.5;
|
|
const qrY = (canvas.height - qrSize) * 0.73;
|
|
|
|
ctx.drawImage(qrImg, qrX, qrY, qrSize, qrSize);
|
|
document.body.removeChild(qrDiv); // 清理 DOM
|
|
|
|
// 返回合成后的图片
|
|
resolve(canvas.toDataURL("image/png"));
|
|
};
|
|
} else {
|
|
reject("二维码生成失败");
|
|
}
|
|
}, 500);
|
|
};
|
|
|
|
poster.onerror = () => reject("海报图片加载失败");
|
|
});
|
|
}
|
|
generatePosterWithQR("img_poster.jpg", "https://example.com")
|
|
.then((imageUrl) => {
|
|
console.log("合成图片地址:", imageUrl);
|
|
|
|
// 你可以直接设置到 <img> 标签
|
|
document.getElementById("resultImage").src = imageUrl;
|
|
|
|
// 或者提供下载功能
|
|
const link = document.createElement("a");
|
|
link.href = imageUrl;
|
|
link.download = "final_poster.png";
|
|
link.innerText = "下载合成图片";
|
|
document.body.appendChild(link);
|
|
})
|
|
.catch((error) => console.error("生成失败:", error));
|
|
</script>
|
|
</body>
|
|
|
|
</html> |