qrcode/script.js
2025-03-07 15:26:41 +08:00

278 lines
9.5 KiB
JavaScript

document.addEventListener("DOMContentLoaded", function () {
// 缓存DOM元素
const qrContent = document.getElementById("qrContent");
const qrTitle = document.getElementById("qrTitle");
const centerText = document.getElementById("centerText");
const generateBtn = document.getElementById("generateBtn");
const printBtn = document.getElementById("printBtn");
const qrcodeDiv = document.getElementById("qrcode");
const deptSelector = $('#deptSelector');
// 初始化表单验证
$('.ui.form').form({
fields: {
qrContent: 'empty'
}
});
// 加载科室数据
fetch('default.json')
.then(response => response.json())
.then(data => {
// 填充科室下拉菜单
const menuItems = data.list.map(dept =>
`<div class="item" data-value="${dept.deptCode}" data-dept-name="${dept.deptName}">${dept.deptName}</div>`
).join('');
deptSelector.find('.menu').html(menuItems);
// 初始化下拉菜单
deptSelector.dropdown({
onChange: function(value) {
if (!value) return;
const deptName = $(this).find(`.item[data-value="${value}"]`).attr('data-dept-name');
// 生成URL
let url = data.baseUrl;
if (data.type === 'searchParams') {
url += `?deptCode=${value}&deptName=${deptName}`;
} else {
url += `/${value}`;
}
qrContent.value = url;
// 更新标题和底部文字
if (!qrTitle.value.trim()) {
qrTitle.value = data.title;
}
centerText.value = deptName;
// 自动生成二维码
generateQRCode();
}
});
// 保存配置数据
window.configData = data;
})
.catch(error => {
console.error('加载科室数据失败:', error);
alert('加载科室数据失败,请刷新页面重试');
});
// 生成按钮点击事件
generateBtn.addEventListener("click", function() {
if (!qrContent.value.trim()) {
alert('请输入要生成二维码的内容');
return;
}
generateQRCode();
});
// 打印按钮点击事件
printBtn.addEventListener("click", function() {
if (!qrContent.value.trim()) {
alert('请先输入内容并生成二维码再打印');
return;
}
if (!qrcodeDiv.querySelector('canvas')) {
generateQRCode();
setTimeout(preparePrintAndPrint, 300);
} else {
preparePrintAndPrint();
}
});
// 准备打印并执行打印
function preparePrintAndPrint() {
const canvas = qrcodeDiv.querySelector('canvas');
if (!canvas) {
alert('生成二维码失败,请重试');
return;
}
const printContainer = document.getElementById('print-container');
printContainer.innerHTML = '';
// 创建打印专用的大尺寸二维码
const printCanvas = document.createElement('canvas');
printCanvas.width = 750; // A4纸宽度的大约90%
const title = qrTitle.value.trim();
const text = centerText.value.trim();
// 计算尺寸
const titleSize = 32;
const qrSize = 600;
const textSize = 24;
const padding = 40;
// 计算文字行数和高度
const textLines = text ? text.split('\n').length : 0;
const textHeight = textLines * textSize * 1.5;
// 设置画布高度
printCanvas.height = (title ? titleSize * 2 : 0) + qrSize + (text ? textHeight + padding : 0) + padding * 2;
// 获取上下文并填充背景
const ctx = printCanvas.getContext('2d');
ctx.fillStyle = '#ffffff';
ctx.fillRect(0, 0, printCanvas.width, printCanvas.height);
// 绘制标题
let yPos = padding;
if (title) {
ctx.font = `bold ${titleSize}px "Microsoft YaHei", sans-serif`;
ctx.fillStyle = '#333333';
ctx.textAlign = 'center';
ctx.textBaseline = 'top';
ctx.fillText(title, printCanvas.width / 2, yPos);
yPos += titleSize * 2;
}
// 重新生成高质量二维码
const tempQR = document.createElement('div');
new QRCode(tempQR, {
text: qrContent.value,
width: qrSize,
height: qrSize,
colorDark: '#000000',
colorLight: '#ffffff',
correctLevel: QRCode.CorrectLevel.H
});
// 等待二维码生成
setTimeout(() => {
try {
const qrImage = tempQR.querySelector('canvas');
const xPos = (printCanvas.width - qrSize) / 2;
// 绘制二维码
ctx.drawImage(qrImage, xPos, yPos);
yPos += qrSize + padding;
// 绘制底部文字
if (text) {
ctx.font = `${textSize}px "Microsoft YaHei", sans-serif`;
ctx.fillStyle = '#333333';
ctx.textAlign = 'center';
text.split('\n').forEach((line, i) => {
ctx.fillText(line, printCanvas.width / 2, yPos + (textSize * 1.5 * i));
});
}
printContainer.appendChild(printCanvas);
window.print();
} catch (err) {
console.error('打印准备失败:', err);
alert('打印准备失败,请重试');
}
}, 200);
}
function generateQRCode() {
qrcodeDiv.innerHTML = "";
// 获取预览容器的尺寸
const previewContainer = document.querySelector('.preview-content');
const containerWidth = previewContainer.offsetWidth;
const containerHeight = previewContainer.offsetHeight;
// 计算二维码大小
const qrWidth = Math.min(containerWidth * 0.9, containerHeight * 0.7);
// 文字大小
const titleSize = Math.max(24, Math.floor(qrWidth * .06));
const textSize = Math.max(18, Math.floor(qrWidth * .05));
const padding = Math.floor(qrWidth * .08);
const title = qrTitle.value.trim();
const text = centerText.value.trim();
// 计算二维码实际大小
const qrImageSize = Math.min(qrWidth * .8, containerHeight * .6);
// 计算高度
const titleHeight = title ? titleSize + padding : 0;
const textLines = text ? text.split('\n').length : 0;
const textHeight = text ? (textSize * textLines * 1.5 + padding) : padding;
const totalHeight = titleHeight + qrImageSize + textHeight;
// 创建画布
const canvas = document.createElement('canvas');
canvas.width = qrWidth;
canvas.height = totalHeight;
const ctx = canvas.getContext('2d');
ctx.fillStyle = '#ffffff';
ctx.fillRect(0, 0, canvas.width, canvas.height);
// 绘制标题
let yPos = padding/2;
if (title) {
ctx.font = `bold ${titleSize}px "Microsoft YaHei", sans-serif`;
ctx.fillStyle = '#333333';
ctx.textAlign = 'center';
ctx.textBaseline = 'top';
ctx.fillText(title, qrWidth/2, yPos);
yPos += titleSize + padding/2;
}
// 生成二维码
const tempDiv = document.createElement('div');
new QRCode(tempDiv, {
text: qrContent.value,
width: qrImageSize,
height: qrImageSize,
colorDark: "#000000",
colorLight: "#ffffff",
correctLevel: QRCode.CorrectLevel.H
});
// 绘制二维码和文字
setTimeout(() => {
const qrImage = tempDiv.querySelector('canvas');
if (!qrImage) return;
// 绘制二维码
const xOffset = (qrWidth - qrImageSize) / 2;
ctx.drawImage(qrImage, xOffset, yPos);
yPos += qrImageSize + padding/2;
// 绘制底部文字
if (text) {
const lines = text.split('\n');
ctx.font = `${textSize}px "Microsoft YaHei", sans-serif`;
ctx.fillStyle = '#333333';
ctx.textAlign = 'center';
lines.forEach((line, i) => {
ctx.fillText(line, qrWidth/2, yPos + (textSize * 1.5 * i));
});
}
qrcodeDiv.appendChild(canvas);
}, 100);
}
// 窗口调整时重新生成二维码
window.addEventListener('resize', debounce(() => {
if (qrContent.value.trim() && qrcodeDiv.childElementCount > 0) {
generateQRCode();
}
}, 300));
// 防抖函数
function debounce(func, wait) {
let timeout;
return function() {
clearTimeout(timeout);
timeout = setTimeout(func, wait);
};
}
});