feat: 新增添加文本功能,支持多文本;fix: 修复保存预览失败
This commit is contained in:
43
js/script.js
43
js/script.js
@@ -3,6 +3,7 @@
|
||||
const fileInput = document.getElementById('fileInput');
|
||||
const addImageBtn = document.getElementById('addImageBtn');
|
||||
const addOverlayBtn = document.getElementById('addOverlayBtn');
|
||||
const addTextBtn = document.getElementById('addTextBtn');
|
||||
const saveBtn = document.getElementById('saveBtn');
|
||||
const imageContainer = document.getElementById('imageContainer');
|
||||
const bgLayer = document.getElementById('bgLayer');
|
||||
@@ -64,6 +65,11 @@
|
||||
overlayInput.value = '';
|
||||
});
|
||||
|
||||
// 添加文本按钮
|
||||
addTextBtn.addEventListener('click', () => {
|
||||
addTextInput();
|
||||
});
|
||||
|
||||
// 文件选择
|
||||
fileInput.addEventListener('change', (e) => {
|
||||
const file = e.target.files[0];
|
||||
@@ -179,6 +185,30 @@
|
||||
reader.readAsDataURL(file);
|
||||
}
|
||||
|
||||
// 添加文本输入框
|
||||
function addTextInput() {
|
||||
const container = imageContainer;
|
||||
const containerWidth = container.clientWidth;
|
||||
const containerHeight = container.clientHeight;
|
||||
|
||||
const textEl = document.createElement('div');
|
||||
textEl.className = 'text-input';
|
||||
textEl.contentEditable = 'false';
|
||||
textEl.textContent = '新文本';
|
||||
|
||||
const left = Math.random() * (containerWidth * 0.6) + containerWidth * 0.1;
|
||||
const top = Math.random() * (containerHeight * 0.6) + containerHeight * 0.1;
|
||||
textEl.style.left = (left / containerWidth * 100) + '%';
|
||||
textEl.style.top = (top / containerHeight * 100) + '%';
|
||||
|
||||
const inputLayer = container.querySelector('.preview-input-layer');
|
||||
inputLayer.appendChild(textEl);
|
||||
|
||||
initInput(textEl);
|
||||
|
||||
selectInput(textEl);
|
||||
}
|
||||
|
||||
// 加载层叠图
|
||||
function loadOverlayImage(file) {
|
||||
const reader = new FileReader();
|
||||
@@ -1543,9 +1573,10 @@
|
||||
async function generateCanvas() {
|
||||
const canvas = exportCanvas;
|
||||
const ctx = canvas.getContext('2d');
|
||||
const container = imageContainer;
|
||||
|
||||
const containerWidth = imageContainer.clientWidth;
|
||||
const containerHeight = imageContainer.clientHeight;
|
||||
const containerWidth = container.clientWidth;
|
||||
const containerHeight = container.clientHeight;
|
||||
|
||||
canvas.width = containerWidth;
|
||||
canvas.height = containerHeight;
|
||||
@@ -1562,9 +1593,11 @@
|
||||
// 绘制层叠图(等待图片加载完成)
|
||||
await drawOverlayImages(ctx);
|
||||
|
||||
// 绘制文字
|
||||
drawTextOnCanvas(ctx, input1);
|
||||
drawTextOnCanvas(ctx, input2);
|
||||
// 绘制文字(动态获取所有文本输入框)
|
||||
const textInputs = container.querySelectorAll('.preview-input-layer .text-input');
|
||||
textInputs.forEach(textInput => {
|
||||
drawTextOnCanvas(ctx, textInput);
|
||||
});
|
||||
|
||||
return canvas;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user