| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486 |
- <template>
- <div class="app-container">
- <div class="tool-card">
- <div class="converter-layout">
- <!-- 右侧: 预览 & Canvas 结果 -->
- <div id="captureTarget" style="position: fixed; left: -100000px">
- <div v-html="editableHtml"> </div>
- </div>
- <div class="preview-panel">
- <div class="canvas-result">
- <canvas id="outputCanvas" v-show="canvasGenerated"></canvas>
- <!-- <div class="canvas-buttons" v-if="canvasGenerated">
- <button @click="downloadCanvasAsImage" class="download">
- 📥 下载图片
- </button>
- <button @click="exportToPDF" class="pdf"> 📄 导出PDF </button>
- <button @click="printCanvas" class="print"> 🖨️ 打印 </button>
- </div> -->
- </div>
- </div>
- </div>
- </div>
- <!-- 图片素材区域 -->
- <div class="images-panel">
- <!-- 公用章 -->
- <div class="seal-section">
- <div class="panel-title">公用章</div>
- <div class="images-grid">
- <div
- v-for="(img, index) in publicImages"
- :key="'public-' + index"
- class="drag-item"
- draggable="true"
- @dragstart="handleDragStart($event, img, index, 'public')"
- >
- <img :src="img.imgUrl" :alt="img.name" />
- <div class="drag-item-name">{{ img.name }}</div>
- </div>
- <div v-if="!publicImages.length" class="no-data">暂无公用章</div>
- </div>
- </div>
- <!-- 个人章 -->
- <div class="seal-section">
- <div class="panel-title">个人章</div>
- <div class="images-grid">
- <div
- v-for="(img, index) in privateImages"
- :key="'private-' + index"
- class="drag-item"
- draggable="true"
- @dragstart="handleDragStart($event, img, index, 'private')"
- >
- <img :src="img.imgUrl" :alt="img.name" />
- <div class="drag-item-name">{{ img.name }}</div>
- </div>
- <div v-if="!privateImages.length" class="no-data">暂无个人章</div>
- </div>
- </div>
- </div>
- </div>
- </template>
- <script>
- import {
- getSealPage,
- getPrivateSealPage
- } from '@/api/bpm/components/sealManagement';
- import { getUserDetail } from '@/api/system/organization/index';
- // 引入 html2canvas 和 jsPDF
- import html2canvas from 'html2canvas';
- import jsPDF from 'jspdf';
- // const imageUrl = [
- // require('@/assets/0.jpg'),
- // require('@/assets/1.jpg'),
- // require('@/assets/2.jpg'),
- // require('@/assets/3.jpg'),
- // require('@/assets/4.jpg'),
- // require('@/assets/5.jpg')
- // ]; // 使用相对路径或别名路径
- // // 默认精美的示例HTML + CSS (内联样式丰富,展示能力)
- // const DEFAULT_HTML = `
- // <div class="container">
- // <div class="img-area">
- // <img class="my-photo" alt="loading" src="${imageUrl[0]}">
- // </div>
- // <div class="img-area">
- // <img class="my-photo" alt="loading" src="${imageUrl[1]}">
- // </div>
- // <div class="img-area">
- // <img class="my-photo" alt="loading" src="${imageUrl[2]}">
- // </div> <div class="img-area">
- // <img class="my-photo" alt="loading" src="${imageUrl[3]}">
- // </div> <div class="img-area">
- // <img class="my-photo" alt="loading" src="${imageUrl[4]}">
- // </div> <div class="img-area">
- // <img class="my-photo" alt="loading" src="${imageUrl[5]}">
- // </div>
- // </div>
- // `;
- export default {
- name: 'HtmlToCanvas',
- data() {
- return {
- editableHtml: '',
- canvasGenerated: false,
- publicImages: [],
- privateImages: [],
- droppedImages: [],
- selectedImage: null,
- baseCanvasData: null, // 缓存基础内容的 Canvas 数据
- _isMoving: false, // 是否正在移动图片
- _currentMoveImageId: null, // 当前正在移动的图片ID
- _moveHandler: null, // 移动事件处理函数引用
- _mouseUpHandler: null, // 鼠标释放事件处理函数引用
- _dragOverHandler: null, // dragover事件处理函数引用
- _dropHandler: null, // drop事件处理函数引用
- _contextMenuHandler: null // contextmenu事件处理函数引用
- };
- },
- created() {
- // 竞态控制字段(非响应式,挂在实例上避免响应式开销)
- this._renderSeq = 0; // 渲染序号,用于竞态控制
- this._lastRenderPromise = null; // 最近一次渲染完成的 Promise
- this._renderResolve = null; // 最近一次渲染的 resolve 回调
- this._renderReject = null; // 最近一次渲染的 reject 回调
- // 获取公用章列表
- getSealPage({
- size: 999,
- pageNum: 1,
- status: 1,
- approvalStatus: 2,
- sealHolderId: this.$store.state.user.info.userId
- }).then((res) => {
- this.publicImages = res.list;
- });
- // 获取个人章列表
- getUserDetail(this.$store.state.user.info.userId).then((res) => {
- if (res.signature?.[0]) {
- this.privateImages = [
- {
- imgUrl: res.signature[0].url,
- name: res.name
- }
- ];
- console.log(this.privateImages, 'this.privateImages ');
- }
- });
- },
- mounted() {
- // 组件挂载后自动渲染一次
- this.$nextTick(() => {
- this.renderToCanvas();
- });
- // 保存组件实例引用,用于事件处理器
- window._aaComponentInstance = this;
- // 创建全局安全移除函数
- window._safeRemoveElement = function (element) {
- try {
- if (
- element &&
- element.parentNode &&
- document.body.contains(element)
- ) {
- element.parentNode.removeChild(element);
- return true;
- }
- } catch (err) {
- console.warn('安全移除元素时发生警告:', err);
- }
- return false;
- };
- },
- beforeDestroy() {
- // 清理移动事件监听器
- this._cancelMove();
- // 清理 Canvas 事件监听器
- const canvas = document.getElementById('outputCanvas');
- if (canvas) {
- if (this._dragOverHandler) {
- canvas.removeEventListener('dragover', this._dragOverHandler);
- }
- if (this._dropHandler) {
- canvas.removeEventListener('drop', this._dropHandler);
- }
- if (this._contextMenuHandler) {
- canvas.removeEventListener('contextmenu', this._contextMenuHandler);
- }
- }
- // 清理引用
- if (window._aaComponentInstance === this) {
- window._aaComponentInstance = null;
- }
- if (window._safeRemoveElement) {
- window._safeRemoveElement = null;
- }
- },
- methods: {
- // 获取组件实例
- getComponentInstance() {
- return window._aaComponentInstance || this;
- },
- // 安全的移除DOM元素
- safeRemoveElement(elementId) {
- try {
- const element = document.getElementById(elementId);
- if (window._safeRemoveElement) {
- return window._safeRemoveElement(element);
- }
- // 回退方案
- if (
- element &&
- element.parentNode &&
- document.body.contains(element)
- ) {
- element.parentNode.removeChild(element);
- return true;
- }
- return false;
- } catch (err) {
- console.warn(`移除元素 ${elementId} 时发生警告:`, err);
- return false;
- }
- },
- // 安全移除所有菜单
- safeRemoveAllMenus() {
- try {
- const existingMenus = document.querySelectorAll('[id^="menu_"]');
- // 使用倒序循环,避免在移除时影响NodeList
- for (let i = existingMenus.length - 1; i >= 0; i--) {
- const menu = existingMenus[i];
- if (menu && document.body.contains(menu) && menu.parentNode) {
- try {
- menu.parentNode.removeChild(menu);
- } catch (err) {
- console.warn('移除菜单时发生警告:', err);
- }
- }
- }
- } catch (err) {
- console.warn('移除所有菜单时发生错误:', err);
- }
- },
- // 设置 Canvas 拖放区域和点击事件
- setupCanvasDropZone() {
- const canvas = document.getElementById('outputCanvas');
- if (!canvas) {
- console.log('Canvas 元素不存在');
- return;
- }
- console.log('设置拖放区域和点击事件,Canvas ID:', canvas.id);
- console.log('Canvas 尺寸:', canvas.width, 'x', canvas.height);
- console.log(
- 'Canvas 可见性:',
- canvas.style.display,
- canvas.style.visibility
- );
- console.log('Canvas 位置:', canvas.getBoundingClientRect());
- // 先移除旧的事件监听器,防止重复绑定
- if (this._dragOverHandler) {
- canvas.removeEventListener('dragover', this._dragOverHandler);
- }
- if (this._dropHandler) {
- canvas.removeEventListener('drop', this._dropHandler);
- }
- if (this._contextMenuHandler) {
- canvas.removeEventListener('contextmenu', this._contextMenuHandler);
- }
- // 创建事件处理函数并保存引用
- this._dragOverHandler = (e) => {
- e.preventDefault();
- e.dataTransfer.dropEffect = 'copy';
- };
- this._dropHandler = (e) => {
- e.preventDefault();
- console.log('触发 drop 事件');
- const imageData = e.dataTransfer.getData('imageData');
- console.log('获取到的 imageData:', imageData);
- if (imageData) {
- const data = JSON.parse(imageData);
- console.log('解析后的数据:', data);
- // 计算 Canvas 坐标到实际像素坐标的比例
- const rect = canvas.getBoundingClientRect();
- const scaleX = canvas.width / rect.width;
- const scaleY = canvas.height / rect.height;
- // 计算点击位置相对于 Canvas 的坐标(实际像素坐标)
- const x = e.offsetX * scaleX;
- const y = e.offsetY * scaleY;
- this.addImageToCanvas(data, x, y);
- }
- };
- this._contextMenuHandler = (e) => {
- e.preventDefault();
- this.handleCanvasRightClick(e);
- };
- // 添加新的事件监听器
- canvas.addEventListener('dragover', this._dragOverHandler);
- canvas.addEventListener('drop', this._dropHandler);
- canvas.addEventListener('contextmenu', this._contextMenuHandler);
- },
- // 处理拖拽开始
- handleDragStart(e, img, index, type) {
- const data = {
- url: img.imgUrl,
- name: img.name,
- version: img.version,
- imgId: type == 'public' ? img.id : '',
- sealType: type // 传递签章类型
- };
- e.dataTransfer.setData('imageData', JSON.stringify(data));
- e.dataTransfer.effectAllowed = 'copy';
- console.log('拖拽开始:', data);
- },
- // 添加图片到 Canvas
- addImageToCanvas(data, x, y) {
- const canvas = document.getElementById('outputCanvas');
- if (!canvas || !this.canvasGenerated) {
- console.log('请先渲染 Canvas');
- return;
- }
- console.log('Canvas 尺寸:', canvas.width, canvas.height);
- console.log('拖放位置:', x, y);
- const ctx = canvas.getContext('2d');
- const img = new Image();
- img.crossOrigin = 'anonymous';
- img.onload = () => {
- console.log('图片加载成功,原始尺寸:', img.width, img.height);
- // 根据签章类型设置尺寸:公用章 120x120,个人章 120x40
- let width, height;
- if (data.sealType === 'private') {
- width = 210;
- height = 70;
- } else {
- width = 200;
- height = 200;
- }
- const posX = x - width / 2;
- const posY = y - height / 2;
- console.log('绘制位置:', posX, posY, '尺寸:', width, height);
- // 绘制图片
- ctx.drawImage(img, posX, posY, width, height);
- const imageId = `img_${Date.now()}_${Math.random()
- .toString(36)
- .substr(2, 9)}`;
- this.droppedImages.push({
- id: imageId,
- imgId: data.imgId,
- imgUrl: data.url,
- version: data.version,
- name:data.name,
- x: posX,
- y: posY,
- width,
- height,
- originalWidth: img.width,
- originalHeight: img.height,
- sealType: data.sealType
- });
- console.log('已添加的图片数量:', this.droppedImages.length);
- this.$message({
- showClose: true,
- message: '操作成功',
- type: 'success'
- });
- // 设置图片可再次拖动和调整(通过右键菜单)
- // 不再创建覆盖层,仅通过右键菜单操作
- };
- img.onerror = (err) => {
- console.error('图片加载失败:', err);
- this.$message({
- showClose: true,
- message: '操作失败',
- type: 'error'
- });
- // this.showMessage('⚠️ 图片加载失败', 'error');
- };
- img.src = data.url;
- },
- // 重新绘制整个 Canvas
- redrawCanvas() {
- const canvas = document.getElementById('outputCanvas');
- if (!canvas || !this.canvasGenerated) return;
- const ctx = canvas.getContext('2d');
- try {
- // 清空 Canvas
- ctx.clearRect(0, 0, canvas.width, canvas.height);
- // 如果有缓存的基础内容,直接绘制
- if (this.baseCanvasData) {
- ctx.drawImage(this.baseCanvasData, 0, 0);
- } else {
- // 如果没有缓存,重新渲染基础内容
- console.warn('没有缓存的基础内容,可能需要重新渲染');
- return;
- }
- // 重新绘制所有拖入的图片
- this.droppedImages.forEach((image) => {
- const img = new Image();
- img.onload = () => {
- ctx.drawImage(img, image.x, image.y, image.width, image.height);
- };
- img.src = image.imgUrl;
- });
- console.log(
- 'Canvas 已快速重绘,包含基础内容和',
- this.droppedImages.length,
- '张图片'
- );
- // 确保事件监听仍然有效
- setTimeout(() => {
- this.setupCanvasDropZone();
- }, 100);
- } catch (error) {
- console.error('重新绘制 Canvas 失败:', error);
- }
- },
- // 显示图片控制菜单
- showImageControls(imageId, x, y) {
- console.log('显示图片控制菜单,位置:', x, y, '图片ID:', imageId);
- // 保存组件实例引用
- const self = this;
- // 先移除可能存在的其他菜单
- this.safeRemoveAllMenus();
- // 定义菜单选项(使用局部变量 self)
- const options = [
- { text: '放大', action: () => self.resizeImage(imageId, 1.2) },
- { text: '缩小', action: () => self.resizeImage(imageId, 0.8) },
- { text: '移动', action: () => self.startMoveImage(imageId, x, y) },
- { text: '删除', action: () => self.removeImage(imageId) }
- ];
- const menu = document.createElement('div');
- menu.id = `menu_${imageId}`;
- menu.style.position = 'fixed';
- // 调整位置,避免菜单超出屏幕边界
- const menuWidth = 120;
- const menuHeight = options.length * 40 + 16; // 估算高度
- let left = x;
- let top = y;
- // 如果菜单会超出右侧边界,向左移动
- if (left + menuWidth > window.innerWidth) {
- left = window.innerWidth - menuWidth - 10;
- }
- // 如果菜单会超出底部边界,向上移动
- if (top + menuHeight > window.innerHeight) {
- top = window.innerHeight - menuHeight - 10;
- }
- menu.style.left = `${left}px`;
- menu.style.top = `${top}px`;
- menu.style.background = 'white';
- menu.style.border = '1px solid #e2e8f0';
- menu.style.borderRadius = '8px';
- menu.style.padding = '8px 0';
- menu.style.boxShadow = '0 4px 12px rgba(0, 0, 0, 0.1)';
- menu.style.zIndex = '9999'; // 使用更高的 z-index
- menu.style.minWidth = `${menuWidth}px`;
- menu.style.opacity = '1';
- menu.style.visibility = 'visible';
- menu.style.display = 'block';
- console.log('菜单位置 - 原始:', x, y, '调整后:', left, top);
- options.forEach((option) => {
- const item = document.createElement('div');
- item.innerText = option.text;
- item.style.padding = '8px 16px';
- item.style.cursor = 'pointer';
- item.style.fontSize = '14px';
- item.style.color = '#374151';
- item.addEventListener('mouseenter', () => {
- item.style.background = '#f3f4f6';
- });
- item.addEventListener('mouseleave', () => {
- item.style.background = 'white';
- });
- item.addEventListener('click', () => {
- option.action();
- // 直接移除当前菜单
- const menuToRemove = document.getElementById(`menu_${imageId}`);
- if (window._safeRemoveElement) {
- window._safeRemoveElement(menuToRemove);
- }
- });
- menu.appendChild(item);
- });
- document.body.appendChild(menu);
- console.log('菜单已添加到 DOM,父元素:', menu.parentElement?.tagName);
- // 点击其他地方关闭菜单
- const closeMenu = (e) => {
- console.log('closeMenu 被调用,目标:', e.target);
- const currentMenu = document.getElementById(`menu_${imageId}`);
- if (!currentMenu || !document.body.contains(currentMenu)) {
- // 菜单已经不存在,移除监听器
- document.removeEventListener('click', closeMenu);
- return;
- }
- if (e.target !== currentMenu && !currentMenu.contains(e.target)) {
- // 使用全局安全函数移除菜单
- if (window._safeRemoveElement) {
- window._safeRemoveElement(currentMenu);
- }
- document.removeEventListener('click', closeMenu);
- }
- };
- setTimeout(() => {
- console.log('添加全局点击监听器');
- document.addEventListener('click', closeMenu);
- }, 0);
- },
- // 调整图片大小
- resizeImage(imageId, factor) {
- const imageIndex = this.droppedImages.findIndex(
- (img) => img.id === imageId
- );
- if (imageIndex === -1) return;
- const image = this.droppedImages[imageIndex];
- image.width *= factor;
- image.height *= factor;
- this.redrawCanvas();
- },
- // 处理 Canvas 右键点击
- handleCanvasRightClick(e) {
- console.log('Canvas 右键点击事件触发');
- const canvas = document.getElementById('outputCanvas');
- if (!canvas) {
- console.log('Canvas 元素不存在');
- return;
- }
- console.log(
- 'Canvas 元素存在,droppedImages 数量:',
- this.droppedImages.length
- );
- if (this.droppedImages.length === 0) {
- console.log('没有已添加的图片');
- return;
- }
- const rect = canvas.getBoundingClientRect();
- console.log('Canvas 边界矩形:', rect);
- const scaleX = canvas.width / rect.width;
- const scaleY = canvas.height / rect.height;
- // 计算点击位置相对于 Canvas 的坐标
- const clickX = (e.clientX - rect.left) * scaleX;
- const clickY = (e.clientY - rect.top) * scaleY;
- console.log('右键点击位置 - 屏幕:', e.clientX, e.clientY);
- console.log('右键点击位置 - Canvas相对:', clickX, clickY);
- // 查找点击到的图片
- let clickedImage = null;
- for (const image of this.droppedImages) {
- console.log(
- '检查图片:',
- image.id,
- '位置:',
- image.x,
- image.y,
- '尺寸:',
- image.width,
- image.height
- );
- if (
- clickX >= image.x &&
- clickX <= image.x + image.width &&
- clickY >= image.y &&
- clickY <= image.y + image.height
- ) {
- clickedImage = image;
- break;
- }
- }
- if (clickedImage) {
- console.log('点击到图片:', clickedImage.id);
- this.showImageControls(clickedImage.id, e.clientX, e.clientY);
- } else {
- console.log('未点击到任何图片');
- // 可以在这里添加其他右键功能,比如添加新图片等
- }
- },
- // 开始移动图片
- startMoveImage(imageId, menuX, menuY) {
- console.log('开始移动图片,图片ID:', imageId);
- // 关闭菜单
- this.safeRemoveElement(`menu_${imageId}`);
- const canvas = document.getElementById('outputCanvas');
- if (!canvas) {
- console.error('Canvas 元素未找到');
- return;
- }
- const imageIndex = this.droppedImages.findIndex(
- (img) => img.id === imageId
- );
- if (imageIndex === -1) {
- console.error('图片未找到,ID:', imageId);
- return;
- }
- const image = this.droppedImages[imageIndex];
- console.log('找到图片:', image);
- // 如果已经在移动中,先移除旧的事件监听器
- if (this._isMoving) {
- this._cancelMove();
- }
- // 设置移动状态标志
- this._isMoving = true;
- this._currentMoveImageId = imageId;
- // 创建一个临时指示器
- const indicator = document.createElement('div');
- indicator.id = `move_indicator_${imageId}`;
- indicator.style.position = 'fixed';
- indicator.style.left = `${menuX}px`;
- indicator.style.top = `${menuY}px`;
- indicator.style.width = '40px';
- indicator.style.height = '40px';
- indicator.style.background = 'rgba(59, 130, 246, 0.3)';
- indicator.style.border = '2px dashed #3b82f6';
- indicator.style.borderRadius = '50%';
- indicator.style.zIndex = '3000';
- indicator.style.pointerEvents = 'none';
- document.body.appendChild(indicator);
- console.log('指示器已创建并添加到DOM');
- // 显示提示
- this.$message({
- showClose: true,
- message: '📍 移动鼠标调整位置,释放鼠标完成移动',
- type: 'info'
- });
- // 保存事件处理函数引用,用于后续移除
- this._moveHandler = (e) => {
- console.log('moveHandler 被调用,鼠标位置:', e.clientX, e.clientY);
- const rect = canvas.getBoundingClientRect();
- const scaleX = canvas.width / rect.width;
- const scaleY = canvas.height / rect.height;
- // 计算相对于 canvas 的位置
- const newX = (e.clientX - rect.left) * scaleX - image.width / 2;
- const newY = (e.clientY - rect.top) * scaleY - image.height / 2;
- // 限制在 canvas 范围内
- image.x = Math.max(0, Math.min(newX, canvas.width - image.width));
- image.y = Math.max(0, Math.min(newY, canvas.height - image.height));
- // 更新指示器位置
- indicator.style.left = `${e.clientX - 20}px`;
- indicator.style.top = `${e.clientY - 20}px`;
- // 使用组件实例引用
- const component = window._aaComponentInstance || this;
- if (component && component.redrawCanvas) {
- component.redrawCanvas();
- }
- };
- this._mouseUpHandler = (e) => {
- console.log(
- 'mouseUpHandler 被调用,位置:',
- e.clientX,
- e.clientY,
- '目标:',
- e.target
- );
- // 无论在哪里释放鼠标,都完成移动
- console.log('鼠标释放,完成移动');
- // 确保只处理一次
- if (indicator.parentNode) {
- console.log('指示器仍在DOM中,移除事件监听器');
- document.removeEventListener('mousemove', this._moveHandler);
- document.removeEventListener('mouseup', this._mouseUpHandler);
- indicator.remove();
- // 重置移动状态
- this._isMoving = false;
- this._currentMoveImageId = null;
- this._moveHandler = null;
- this._mouseUpHandler = null;
- // 使用组件实例引用
- const component = window._aaComponentInstance || this;
- if (component) {
- this.$message({
- showClose: true,
- message: '图片已移动',
- type: 'success'
- });
- }
- } else {
- console.log('指示器已不在DOM中');
- }
- };
- // 确保事件只绑定一次
- console.log('绑定事件监听器');
- document.removeEventListener('mousemove', this._moveHandler);
- document.removeEventListener('mouseup', this._mouseUpHandler);
- document.addEventListener('mousemove', this._moveHandler);
- document.addEventListener('mouseup', this._mouseUpHandler);
- },
- // 删除图片
- removeImage(imageId) {
- const imageIndex = this.droppedImages.findIndex(
- (img) => img.id === imageId
- );
- if (imageIndex === -1) return;
- this.droppedImages.splice(imageIndex, 1);
- // 删除控制菜单
- this.safeRemoveElement(`menu_${imageId}`);
- // 如果正在移动这张图片,取消移动状态
- if (this._currentMoveImageId === imageId) {
- this._cancelMove();
- }
- this.redrawCanvas();
- this.$message({
- showClose: true,
- message: '🗑️ 图片已删除',
- type: 'success'
- });
- },
- // 取消移动操作
- _cancelMove() {
- if (this._moveHandler) {
- document.removeEventListener('mousemove', this._moveHandler);
- }
- if (this._mouseUpHandler) {
- document.removeEventListener('mouseup', this._mouseUpHandler);
- }
- // 移除指示器
- if (this._currentMoveImageId) {
- const indicator = document.getElementById(
- `move_indicator_${this._currentMoveImageId}`
- );
- if (indicator && indicator.parentNode) {
- indicator.remove();
- }
- }
- // 重置状态
- this._isMoving = false;
- this._currentMoveImageId = null;
- this._moveHandler = null;
- this._mouseUpHandler = null;
- },
- // 渲染Canvas核心函数
- async renderToCanvas(type) {
- // 竞态保护:记录本次渲染序号与 Promise,供 exportToPDF 等待最新一次渲染完成
- const mySeq = ++this._renderSeq;
- this._lastRenderPromise = new Promise((resolve, reject) => {
- this._renderResolve = resolve;
- this._renderReject = reject;
- });
- const targetElement = document.getElementById('captureTarget');
- if (!targetElement) {
- console.warn('未找到目标元素');
- this._renderReject && this._renderReject(new Error('未找到目标元素'));
- return;
- }
- // 显示加载状态
- const canvasResultDiv = document.querySelector('.canvas-result');
- const originalMsg = canvasResultDiv.querySelector('p');
- if (originalMsg) originalMsg.style.display = 'none';
- // 添加加载提示
- let loadingMsg = document.getElementById('tempLoadingMsg');
- if (!loadingMsg) {
- loadingMsg = document.createElement('div');
- loadingMsg.id = 'tempLoadingMsg';
- loadingMsg.innerText = '⏳ 渲染中,请稍候...';
- loadingMsg.style.padding = '12px';
- loadingMsg.style.color = '#2563eb';
- loadingMsg.style.fontSize = '14px';
- canvasResultDiv.appendChild(loadingMsg);
- }
- try {
- // 使用 html2canvas 进行转换,scale: 2 提高清晰度
- const scale = 2;
- // captureTarget 是隐藏元素(left: -100000px),scrollWidth/Height 偶现为 0,
- // 用 getBoundingClientRect 兜底获取真实宽高,避免渲染出 0 尺寸 canvas
- const rect = targetElement.getBoundingClientRect();
- const targetWidth =
- targetElement.scrollWidth || Math.ceil(rect.width) || 1;
- const targetHeight =
- targetElement.scrollHeight || Math.ceil(rect.height) || 1;
- const canvas = await html2canvas(targetElement, {
- scale: scale, // 2倍分辨率,提高清晰度
- backgroundColor: '#ffffff',
- useCORS: true, // 尝试跨域图片
- logging: false,
- allowTaint: false,
- imageTimeout: 5000,
- windowWidth: targetWidth,
- windowHeight: targetHeight
- });
- // 移除加载提示
- const temp = document.getElementById('tempLoadingMsg');
- if (temp) temp.remove();
- // 获取输出canvas元素并绘制
- const outputCanvas = document.getElementById('outputCanvas');
- outputCanvas.width = canvas.width;
- outputCanvas.height = canvas.height;
- // 使用原始尺寸(去除scale倍数),保持显示比例
- outputCanvas.style.width = canvas.width / scale + 'px';
- outputCanvas.style.height = canvas.height / scale + 'px';
- const ctx = outputCanvas.getContext('2d');
- ctx.clearRect(0, 0, outputCanvas.width, outputCanvas.height);
- ctx.drawImage(canvas, 0, 0);
- // 保存基础内容的 Canvas 数据(用于快速重绘)
- this.baseCanvasData = canvas;
- this.canvasGenerated = true;
- // 设置 Canvas 拖放区域和事件监听
- if (type == 'init') {
- this.setupCanvasDropZone();
- } else {
- this.redrawCanvas();
- }
- // 仅当这是最新一次渲染时才 resolve,避免旧渲染覆盖新状态
- if (mySeq === this._renderSeq && this._renderResolve) {
- this._renderResolve();
- }
- // 显示成功提示
- // this.showMessage('✅ 渲染成功!可下载图片', 'success');
- } catch (error) {
- console.error('html2canvas 渲染失败: ', error);
- const temp = document.getElementById('tempLoadingMsg');
- if (temp) temp.remove();
- this.canvasGenerated = false;
- // 仅当这是最新一次渲染时才 reject
- if (mySeq === this._renderSeq && this._renderReject) {
- this._renderReject(error);
- }
- // this.showMessage('⚠️ 渲染失败,请检查HTML结构或外部资源', 'error');
- }
- },
- // 导出为 PDF(使用 jsPDF)
- async exportToPDF() {
- // 竞态保护:如果正在渲染,等待最新一次渲染完成(最多等 15s),
- // 避免 html2canvas 尚未绘制完成就导出导致偶现失败
- if (this._lastRenderPromise) {
- try {
- await Promise.race([
- this._lastRenderPromise,
- new Promise((_, reject) =>
- setTimeout(() => reject(new Error('等待渲染完成超时')), 15000)
- )
- ]);
- } catch (err) {
- console.error('等待渲染完成失败,跳过导出:', err);
- this.$message && this.$message.error('渲染尚未完成,请稍后重试');
- return;
- }
- }
- const outputCanvas = document.getElementById('outputCanvas');
- if (
- !this.canvasGenerated ||
- !outputCanvas ||
- outputCanvas.width === 0
- ) {
- this.$message && this.$message.error('内容尚未渲染,无法导出PDF');
- return;
- }
- try {
- // 使用 Canvas 的 CSS 尺寸(显示尺寸)
- let cssWidth =
- parseFloat(outputCanvas.style.width) || outputCanvas.width;
- let cssHeight =
- parseFloat(outputCanvas.style.height) || outputCanvas.height;
- // 防止 css 尺寸异常(比如渲染竞态时 style 未设置),兜底用 canvas 实际像素
- if (!cssWidth || !cssHeight || isNaN(cssWidth) || isNaN(cssHeight)) {
- cssWidth = outputCanvas.width;
- cssHeight = outputCanvas.height;
- }
- // 计算需要的降采样比例:
- // jsPDF 最大页面尺寸约 5080mm,按 96dpi 换算约 19200px,留 10% 余量用 17000px
- const MAX_SIDE = 17000;
- let scale = 1;
- const maxSide = Math.max(outputCanvas.width, outputCanvas.height);
- if (maxSide > MAX_SIDE) {
- scale = MAX_SIDE / maxSide;
- }
- // 降采样后从临时 canvas 取图,避免超大图 toDataURL OOM / 超出 jsPDF 限制
- let imgData;
- if (scale < 1) {
- const tempCanvas = document.createElement('canvas');
- tempCanvas.width = Math.round(outputCanvas.width * scale);
- tempCanvas.height = Math.round(outputCanvas.height * scale);
- const tempCtx = tempCanvas.getContext('2d');
- tempCtx.drawImage(
- outputCanvas,
- 0,
- 0,
- tempCanvas.width,
- tempCanvas.height
- );
- imgData = tempCanvas.toDataURL('image/jpeg', 0.95);
- } else {
- imgData = outputCanvas.toDataURL('image/jpeg', 0.95);
- }
- // 创建 PDF 实例,横向或纵向根据 Canvas 尺寸决定
- const orientation = cssWidth > cssHeight ? 'l' : 'p';
- // 使用 'mm' 单位,并根据 CSS 尺寸转换为毫米(保持显示比例)
- // 屏幕 DPI 约 96,1px = 25.4 / 96 mm ≈ 0.2646 mm
- const DPI = 96;
- const pxToMm = 25.4 / DPI;
- const pdfWidth = cssWidth * pxToMm;
- const pdfHeight = cssHeight * pxToMm;
- const pdf = new jsPDF(orientation, 'mm', [pdfWidth, pdfHeight]);
- // 将 Canvas 图片添加到 PDF
- pdf.addImage(imgData, 'JPEG', 0, 0, pdfWidth, pdfHeight);
- // 获取 PDF 文件流并触发事件
- const pdfBlob = pdf.output('blob');
- const pdfFile = new File([pdfBlob], `canvas-${Date.now()}.pdf`, {
- type: 'application/pdf'
- });
- // 触发 PDF 生成事件,父组件可以监听此事件
- this.$emit('pdf-generated', {
- pdfFile,
- droppedImages: this.droppedImages
- });
- // 保存 PDF
- // const timestamp = new Date()
- // .toISOString()
- // .slice(0, 19)
- // .replace(/:/g, '-');
- // pdf.save(`canvas-${timestamp}.pdf`);
- // this.showMessage('✅ PDF 导出成功', 'success');
- } catch (err) {
- console.error('PDF 导出失败', err);
- // this.showMessage('PDF 导出失败,请稍后重试', 'error');
- }
- },
- // 打印 Canvas / 另存为 PDF
- printCanvas() {
- const outputCanvas = document.getElementById('outputCanvas');
- if (
- !this.canvasGenerated ||
- !outputCanvas ||
- outputCanvas.width === 0
- ) {
- // this.showMessage('请先点击"渲染至Canvas"生成图像后再打印', 'error');
- return;
- }
- try {
- // 创建新窗口用于打印
- const printWindow = window.open('', '_blank');
- const dataUrl = outputCanvas.toDataURL('image/png');
- printWindow.document.write(`
- <!DOCTYPE html>
- <html>
- <head>
- <title>打印图片</title>
- <style>
- body {
- margin: 0;
- padding: 20px;
- display: flex;
- justify-content: center;
- align-items: center;
- }
- img {
- max-width: 100%;
- height: auto;
- }
- @media print {
- body {
- padding: 0;
- }
- img {
- max-width: 100%;
- page-break-inside: avoid;
- }
- }
- </style>
- </head>
- <body>
- <img src="${dataUrl}" onload="window.print(); window.close();" />
- </body>
- </html>
- `);
- printWindow.document.close();
- // this.showMessage('✅ 已打开打印窗口,可选择另存为PDF', 'success');
- } catch (err) {
- console.error('打印失败', err);
- // this.showMessage('打印失败,请检查浏览器设置', 'error');
- }
- },
- init(html, data) {
- if (data.droppedImages) {
- this.droppedImages = data.droppedImages;
- this.editableHtml = html;
- this.$nextTick(() => {
- this.renderToCanvas();
- });
- } else {
- this.editableHtml = html;
- this.$nextTick(() => {
- this.renderToCanvas('init');
- });
- }
- }
- }
- };
- </script>
- <style scoped>
- * {
- margin: 0;
- padding: 0;
- box-sizing: border-box;
- }
- .app-container {
- max-width: 1400px;
- width: 100%;
- margin: 0 auto;
- padding: 24px 20px;
- min-height: 100vh;
- display: flex;
- justify-content: center;
- align-items: center;
- background: linear-gradient(145deg, #e0eafc 0%, #cfdef3 100%);
- }
- .tool-card {
- background: rgba(255, 255, 255, 0.92);
- backdrop-filter: blur(2px);
- border-radius: 2rem;
- box-shadow: 0 25px 45px -12px rgba(0, 0, 0, 0.3),
- 0 1px 2px rgba(0, 0, 0, 0.05);
- overflow: hidden;
- padding: 1.8rem 2rem 2rem 2rem;
- width: 100%;
- }
- h1 {
- font-size: 2rem;
- font-weight: 700;
- background: linear-gradient(135deg, #1a2a6c, #3b82f6, #8b5cf6);
- background-clip: text;
- -webkit-background-clip: text;
- color: transparent;
- letter-spacing: -0.3px;
- margin-bottom: 0.35rem;
- }
- .sub {
- color: #4a5568;
- border-left: 4px solid #3b82f6;
- padding-left: 14px;
- margin-bottom: 1.8rem;
- font-weight: 500;
- font-size: 0.95rem;
- }
- .converter-layout {
- display: flex;
- justify-content: center;
- }
- .editor-panel {
- flex: 1.2;
- min-width: 280px;
- background: #f8fafc;
- border-radius: 1.5rem;
- padding: 1.25rem;
- box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
- border: 1px solid #e2e8f0;
- }
- .panel-title {
- font-weight: 600;
- font-size: 1.2rem;
- color: #0f172a;
- margin-bottom: 1rem;
- display: flex;
- align-items: center;
- gap: 8px;
- border-bottom: 2px solid #cbd5e1;
- padding-bottom: 8px;
- }
- .html-editor {
- width: 100%;
- height: 360px;
- background: #1e293b;
- color: #e2e8f0;
- font-family: 'Fira Code', 'Cascadia Code', monospace;
- font-size: 13px;
- line-height: 1.5;
- padding: 1rem;
- border-radius: 1rem;
- border: none;
- resize: vertical;
- outline: none;
- margin-bottom: 1rem;
- box-shadow: inset 0 2px 5px rgba(0, 0, 0, 0.2);
- }
- .html-editor:focus {
- border: 1px solid #3b82f6;
- background: #0f172a;
- }
- .toolbar {
- display: flex;
- gap: 12px;
- flex-wrap: wrap;
- margin-top: 8px;
- margin-bottom: 16px;
- }
- button {
- background: white;
- border: 1px solid #cbd5e1;
- padding: 8px 18px;
- border-radius: 40px;
- font-weight: 600;
- font-size: 0.85rem;
- cursor: pointer;
- transition: 0.2s;
- color: #1e293b;
- display: inline-flex;
- align-items: center;
- gap: 6px;
- box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
- }
- button.primary {
- background: #3b82f6;
- border-color: #3b82f6;
- color: white;
- box-shadow: 0 4px 8px rgba(59, 130, 246, 0.3);
- }
- button.primary:hover {
- background: #2563eb;
- transform: translateY(-1px);
- }
- button.download {
- background: #10b981;
- border-color: #10b981;
- color: white;
- }
- button.download:hover {
- background: #059669;
- transform: translateY(-1px);
- }
- button.pdf {
- background: #8b5cf6;
- border-color: #8b5cf6;
- color: white;
- }
- button.pdf:hover {
- background: #7c3aed;
- transform: translateY(-1px);
- }
- button.print {
- background: #8b5cf6;
- border-color: #8b5cf6;
- color: white;
- }
- button.print:hover {
- background: #7c3aed;
- transform: translateY(-1px);
- }
- .canvas-buttons {
- display: flex;
- gap: 12px;
- justify-content: center;
- margin-top: 16px;
- }
- button:hover {
- background: #f1f5f9;
- transform: translateY(-1px);
- }
- .info-message {
- font-size: 0.8rem;
- color: #2563eb;
- background: #eff6ff;
- padding: 6px 12px;
- border-radius: 40px;
- display: inline-block;
- }
- .preview-panel {
- flex: 1;
- min-width: 0;
- background: #ffffff;
- border-radius: 1.5rem;
- padding: 1.25rem;
- box-shadow: 0 8px 20px rgba(0, 0, 0, 0.08);
- border: 1px solid #eef2ff;
- display: flex;
- flex-direction: column;
- }
- .images-panel {
- flex: 0 0 300px;
- background: #ffffff;
- border-radius: 1.5rem;
- padding: 1.25rem;
- box-shadow: 0 8px 20px rgba(0, 0, 0, 0.08);
- border: 1px solid #eef2ff;
- display: flex;
- flex-direction: column;
- position: fixed;
- right: 2rem;
- top: 40px;
- max-height: calc(100vh - 80px);
- overflow-y: auto;
- z-index: 100;
- }
- .seal-section {
- margin-bottom: 1rem;
- }
- .seal-section:last-child {
- margin-bottom: 0;
- }
- .no-data {
- grid-column: 1 / -1;
- text-align: center;
- color: #94a3b8;
- padding: 20px 0;
- font-size: 14px;
- }
- .images-grid {
- display: grid;
- grid-template-columns: repeat(2, 1fr);
- gap: 12px;
- /* flex: 1; */
- overflow-y: auto;
- }
- .drag-item {
- background: #f8fafc;
- border: 2px solid #e2e8f0;
- border-radius: 12px;
- padding: 8px;
- cursor: move;
- transition: all 0.2s;
- display: flex;
- flex-direction: column;
- align-items: center;
- height: 130px; /* 固定高度:图片80px + 内边距8px*2 + 文字区域 */
- justify-content: space-between;
- }
- .drag-item:hover {
- border-color: #3b82f6;
- background: #eff6ff;
- transform: translateY(-2px);
- box-shadow: 0 4px 12px rgba(59, 130, 246, 0.2);
- }
- .drag-item img {
- width: 100%;
- height: 80px;
- object-fit: contain; /* 改为contain,确保完整显示图片 */
- border-radius: 8px;
- pointer-events: none;
- background-color: #f1f5f9; /* 添加背景色,防止透明图片看不清 */
- }
- .drag-item-name {
- font-size: 12px;
- color: #64748b;
- margin-top: 6px;
- text-align: center;
- overflow: hidden;
- text-overflow: ellipsis;
- white-space: nowrap;
- width: 100%;
- line-height: 1.4;
- padding: 0 4px;
- max-height: 32px; /* 限制文字最大高度 */
- }
- .preview-header {
- display: flex;
- justify-content: space-between;
- align-items: baseline;
- margin-bottom: 1rem;
- flex-wrap: wrap;
- }
- .badge {
- background: #e6f0ff;
- padding: 4px 12px;
- border-radius: 30px;
- font-size: 0.75rem;
- font-weight: 500;
- color: #1e40af;
- }
- .canvas-area {
- background: #f1f5f9;
- border-radius: 1.2rem;
- padding: 1rem;
- text-align: center;
- min-height: 280px;
- }
- .target-element {
- background: white;
- border-radius: 1rem;
- padding: 1rem;
- box-shadow: 0 6px 14px rgba(0, 0, 0, 0.05);
- max-width: 100%;
- overflow: auto;
- }
- hr {
- margin: 0.8rem 0;
- border-color: #e2e8f0;
- }
- .canvas-result {
- margin-top: 1rem;
- background: #ffffffd9;
- border-radius: 1rem;
- padding: 0.8rem;
- text-align: center;
- }
- .canvas-result p {
- font-size: 0.8rem;
- color: #475569;
- }
- canvas {
- border-radius: 12px;
- box-shadow: 0 6px 12px rgba(0, 0, 0, 0.1);
- background: white;
- }
- footer {
- margin-top: 1.5rem;
- text-align: center;
- font-size: 0.75rem;
- color: #334155;
- }
- @media (max-width: 780px) {
- .tool-card {
- padding: 1rem;
- }
- .html-editor {
- height: 260px;
- }
- .converter-layout {
- justify-content: center;
- /* flex-wrap: wrap;
- padding-right: 0;
- gap: 1rem; */
- }
- .images-panel {
- position: relative;
- right: auto;
- top: auto;
- width: 100%;
- max-height: 300px; /* 在小屏幕下限制最大高度 */
- order: 2; /* 在移动端将图片区域放在底部 */
- margin-top: 1rem;
- }
- .drag-item {
- height: 120px; /* 在小屏幕下稍微减小高度 */
- }
- .drag-item img {
- height: 70px; /* 在小屏幕下减小图片高度 */
- }
- }
- </style>
|