import { watch } from 'vue' /** * Canvas 渲染工具类 * 自动监听模板数据变化,渲染到 Canvas,支持元素选中和拖拽 */ class CanvasRenderer { constructor(options = {}) { // 配置 this.config = { dpi: 203, scale: 1, backgroundColor: '#ffffff', gridColor: '#e0e0e0', gridSize: 5, // mm showGrid: true, ...options } // Canvas 相关 this.canvas = null this.ctx = null this.container = null // 渲染状态 this.isRendering = false this.needsRender = false this.lastRenderTime = 0 this.renderDebounce = 16 // 约 60fps // 模板数据 this.templateData = null this.templateTree = null // 交互状态 this.selectedElementId = null this.hoveredElementId = null this.draggingElement = null this.dragStartPos = { x: 0, y: 0 } this.dragElementStartPos = { x: 0, y: 0 } // 转换缓存 this.mmToPixelCache = {} this.elementsCache = new Map() // 事件监听器 this.eventListeners = { select: [], update: [], render: [] } // 边界检查 this.bounds = { minX: 0, minY: 0, maxX: 0, maxY: 0 } } /** * 初始化 Canvas 渲染器 * @param {HTMLCanvasElement} canvas - Canvas 元素 * @param {HTMLElement} container - 容器元素(用于事件) */ initialize(canvas, container) { if (!canvas || !container) { throw new Error('Canvas 和容器元素不能为空') } this.canvas = canvas this.container = container this.ctx = canvas.getContext('2d') // 设置 Canvas 尺寸 this.updateCanvasSize() // 初始化事件监听 this.initEventListeners() // 初始化渲染循环 this.initRenderLoop() console.log('CanvasRenderer 初始化完成') } /** * 设置模板数据并开始监听 * @param {Object} templateStore - 模板 Store(响应式对象) */ setTemplateData(templateStore) { try { if (!templateStore || !templateStore.templateObjects) { console.error('无效的模板数据') return } this.templateData = templateStore // 初始渲染 this.scheduleRender() } catch (error) { console.log(error); } } /** * 更新 Canvas 尺寸 */ updateCanvasSize() { if (!this.canvas || !this.container) return const containerRect = this.container.getBoundingClientRect() const width = containerRect.width const height = containerRect.height // 设置 Canvas 物理像素 const dpr = window.devicePixelRatio || 1 this.canvas.width = width * dpr this.canvas.height = height * dpr this.canvas.style.width = `${width}px` this.canvas.style.height = `${height}px` // 缩放 Canvas 上下文 this.ctx.scale(dpr, dpr) this.scheduleRender() } /** * 初始化事件监听 */ initEventListeners() { if (!this.canvas || !this.container) return // 点击事件 - 选择元素 this.canvas.addEventListener('click', this.handleCanvasClick.bind(this)) // 鼠标移动事件 - 悬停效果 this.canvas.addEventListener('mousemove', this.handleMouseMove.bind(this)) // 鼠标按下事件 - 开始拖拽 this.canvas.addEventListener('mousedown', this.handleMouseDown.bind(this)) // 鼠标松开事件 - 结束拖拽 document.addEventListener('mouseup', this.handleMouseUp.bind(this)) // 鼠标离开事件 this.canvas.addEventListener('mouseleave', this.handleMouseLeave.bind(this)) // 键盘事件 - 删除选中的元素 document.addEventListener('keydown', this.handleKeyDown.bind(this)) // 窗口大小变化 window.addEventListener('resize', this.handleResize.bind(this)) } /** * 移除事件监听 */ removeEventListeners() { if (!this.canvas) return this.canvas.removeEventListener('click', this.handleCanvasClick) this.canvas.removeEventListener('mousemove', this.handleMouseMove) this.canvas.removeEventListener('mousedown', this.handleMouseDown) document.removeEventListener('mouseup', this.handleMouseUp) this.canvas.removeEventListener('mouseleave', this.handleMouseLeave) document.removeEventListener('keydown', this.handleKeyDown) window.removeEventListener('resize', this.handleResize) } /** * 初始化渲染循环 */ initRenderLoop() { const renderFrame = () => { if (this.needsRender) { this.render() this.needsRender = false } requestAnimationFrame(renderFrame) } requestAnimationFrame(renderFrame) } /** * 安排渲染 */ scheduleRender() { this.needsRender = true } /** * 主渲染方法 */ render() { if (!this.canvas || !this.ctx || !this.templateData) return const startTime = performance.now() // 清除画布 this.clearCanvas() // 绘制背景 this.drawBackground() // 绘制网格(如果启用) if (this.config.showGrid) { this.drawGrid() } // 绘制模板 this.drawTemplate() // 绘制选中状态 this.drawSelection() // 绘制悬停状态 this.drawHover() // 绘制边界 this.drawBounds() this.lastRenderTime = performance.now() - startTime // 触发渲染完成事件 this.emit('render', { time: this.lastRenderTime, elements: this.templateData?.templateObjects?.length || 0 }) } /** * 清除画布 */ clearCanvas() { const width = this.canvas.width / (window.devicePixelRatio || 1) const height = this.canvas.height / (window.devicePixelRatio || 1) this.ctx.save() this.ctx.setTransform(1, 0, 0, 1, 0, 0) this.ctx.clearRect(0, 0, width, height) this.ctx.restore() } /** * 绘制背景 */ drawBackground() { const width = this.canvas.width / (window.devicePixelRatio || 1) const height = this.canvas.height / (window.devicePixelRatio || 1) this.ctx.fillStyle = this.config.backgroundColor this.ctx.fillRect(0, 0, width, height) } /** * 绘制网格 */ drawGrid() { const width = this.canvas.width / (window.devicePixelRatio || 1) const height = this.canvas.height / (window.devicePixelRatio || 1) const gridSizePx = this.mmToPixel(this.config.gridSize) this.ctx.strokeStyle = this.config.gridColor this.ctx.lineWidth = 0.5 // 绘制垂直线 for (let x = 0; x <= width; x += gridSizePx) { this.ctx.beginPath() this.ctx.moveTo(x, 0) this.ctx.lineTo(x, height) this.ctx.stroke() } // 绘制水平线 for (let y = 0; y <= height; y += gridSizePx) { this.ctx.beginPath() this.ctx.moveTo(0, y) this.ctx.lineTo(width, y) this.ctx.stroke() } } /** * 绘制模板 */ drawTemplate() { if (!this.templateData?.templateObjects) return // 获取页面元素 const page = this.templateData.templateObjects.find(el => el.name === 'page') if (!page) return // 计算偏移量(居中显示) const containerWidth = this.canvas.width / (window.devicePixelRatio || 1) const containerHeight = this.canvas.height / (window.devicePixelRatio || 1) const pageWidth = this.mmToPixel(page.width) const pageHeight = this.mmToPixel(page.height) this.offsetX = (containerWidth - pageWidth) / 2 this.offsetY = (containerHeight - pageHeight) / 2 // 保存上下文 this.ctx.save() // 应用偏移 this.ctx.translate(this.offsetX, this.offsetY) // 绘制页面背景 this.ctx.fillStyle = '#ffffff' this.ctx.fillRect(0, 0, pageWidth, pageHeight) this.ctx.strokeStyle = '#cccccc' this.ctx.lineWidth = 1 this.ctx.strokeRect(0, 0, pageWidth, pageHeight) // 绘制所有元素 this.templateData.templateObjects.forEach(element => { if (element.name !== 'page') { this.drawElement(element) } }) // 恢复上下文 this.ctx.restore() // 更新边界 this.bounds = { minX: this.offsetX, minY: this.offsetY, maxX: this.offsetX + pageWidth, maxY: this.offsetY + pageHeight } } /** * 绘制单个元素 * @param {Object} element - 元素对象 */ drawElement(element) { const style = this.parseStyle(element.style) // 应用样式 this.ctx.save() // 设置透明度 this.ctx.globalAlpha = style.opacity || 1 // 绘制不同类型元素 switch (element.name) { case 'text': this.drawTextElement(element, style) break case 'barcode': this.drawBarcodeElement(element, style) break case 'image': this.drawImageElement(element, style) break case 'line': this.drawLineElement(element, style) break case 'layout': this.drawLayoutElement(element, style) break default: console.warn(`未知元素类型: ${element.name}`) } // 绘制元素边框(调试用) if (this.config.showDebugInfo) { this.drawElementDebugInfo(element) } this.ctx.restore() } /** * 绘制文本元素 */ drawTextElement(element, style) { const x = this.mmToPixel(element.left || 0) const y = this.mmToPixel(element.top || 0) const width = this.mmToPixel(element.width || 50) const height = this.mmToPixel(element.height || 10) // 设置文本样式 this.ctx.fillStyle = style.color || element.color || '#000000' this.ctx.font = `${style.fontWeight || 'normal'} ${this.mmToPixel(style.fontSize || element.fontSize || 12)}px ${style.fontFamily || element.fontFamily || 'Arial'}` this.ctx.textAlign = style.align || element.align || 'left' this.ctx.textBaseline = 'top' // 绘制文本 const lines = (element.content || '').split('\n') const lineHeight = this.mmToPixel(style.lineHeight || element.lineHeight || element.fontSize || 12) lines.forEach((line, index) => { const lineY = y + (lineHeight * index) // 文本溢出处理 if (style.overflow === 'ellipsis') { const metrics = this.ctx.measureText(line) if (metrics.width > width) { line = this.truncateText(line, width) } } this.ctx.fillText(line, x, lineY) }) } /** * 绘制条码元素(简化版,实际应使用条码库) */ drawBarcodeElement(element, style) { const x = this.mmToPixel(element.left || 0) const y = this.mmToPixel(element.top || 0) const width = this.mmToPixel(element.width || 50) const height = this.mmToPixel(element.height || 20) // 绘制条码背景 this.ctx.fillStyle = '#ffffff' this.ctx.fillRect(x, y, width, height) this.ctx.strokeStyle = '#cccccc' this.ctx.strokeRect(x, y, width, height) // 绘制模拟条码(实际项目应集成条码库) this.ctx.fillStyle = '#000000' for (let i = 0; i < 20; i++) { const barWidth = width / 20 const barHeight = Math.random() * height * 0.8 const barX = x + i * barWidth const barY = y + (height - barHeight) / 2 if (Math.random() > 0.3) { this.ctx.fillRect(barX, barY, barWidth * 0.8, barHeight) } } // 绘制条码文本 if (!element.hideText) { this.ctx.fillStyle = '#000000' this.ctx.font = `${this.mmToPixel(8)}px Arial` this.ctx.textAlign = 'center' this.ctx.textBaseline = 'bottom' this.ctx.fillText(element.content || 'BARCODE', x + width / 2, y + height - 2) } } /** * 绘制图片元素 */ drawImageElement(element, style) { // 简化实现,实际项目需要加载图片 const x = this.mmToPixel(element.left || 0) const y = this.mmToPixel(element.top || 0) const width = this.mmToPixel(element.width || 50) const height = this.mmToPixel(element.height || 50) // 绘制图片占位 this.ctx.fillStyle = '#f0f0f0' this.ctx.fillRect(x, y, width, height) this.ctx.strokeStyle = '#cccccc' this.ctx.strokeRect(x, y, width, height) // 绘制图片图标 this.ctx.fillStyle = '#999999' this.ctx.font = `${this.mmToPixel(10)}px Arial` this.ctx.textAlign = 'center' this.ctx.textBaseline = 'middle' this.ctx.fillText('📷', x + width / 2, y + height / 2) // 绘制图片名称 this.ctx.fillStyle = '#666666' this.ctx.font = `${this.mmToPixel(6)}px Arial` this.ctx.fillText(element.src ? element.src.split('/').pop() : '图片', x + width / 2, y + height + 5) } /** * 绘制线条元素 */ drawLineElement(element, style) { const startX = this.mmToPixel(element.startX || 0) const startY = this.mmToPixel(element.startY || 0) const endX = this.mmToPixel(element.endX || 50) const endY = this.mmToPixel(element.endY || 50) // 设置线条样式 this.ctx.strokeStyle = style.lineColor || element.lineColor || '#000000' this.ctx.lineWidth = this.mmToPixel(style.lineWidth || element.lineWidth || 1) // 设置线条类型 if (style.lineType === 'dashed') { this.ctx.setLineDash([5, 5]) } else { this.ctx.setLineDash([]) } // 绘制线条 this.ctx.beginPath() this.ctx.moveTo(startX, startY) this.ctx.lineTo(endX, endY) this.ctx.stroke() this.ctx.setLineDash([]) // 重置虚线 } /** * 绘制布局容器 */ drawLayoutElement(element, style) { const x = this.mmToPixel(element.left || 0) const y = this.mmToPixel(element.top || 0) const width = this.mmToPixel(element.width || 100) const height = this.mmToPixel(element.height || 100) // 绘制布局背景 this.ctx.fillStyle = style.backgroundColor || 'rgba(200, 200, 255, 0.1)' this.ctx.fillRect(x, y, width, height) // 绘制布局边框 this.ctx.strokeStyle = style.borderColor || '#cccccc' this.ctx.lineWidth = 1 this.ctx.strokeRect(x, y, width, height) } /** * 绘制元素调试信息 */ drawElementDebugInfo(element) { const x = this.mmToPixel(element.left || 0) const y = this.mmToPixel(element.top || 0) const width = this.mmToPixel(element.width || 0) const height = this.mmToPixel(element.height || 0) this.ctx.strokeStyle = '#ff0000' this.ctx.lineWidth = 0.5 this.ctx.strokeRect(x, y, width, height) // 显示元素ID this.ctx.fillStyle = '#ff0000' this.ctx.font = '8px Arial' this.ctx.fillText(element.id.slice(0, 8), x, y - 5) } /** * 绘制选中状态 */ drawSelection() { if (!this.selectedElementId || !this.templateData) return const element = this.templateData.templateObjects.find(el => el.id === this.selectedElementId) if (!element) return this.drawElementHighlight(element, '#409eff', 2) // 绘制控制点 this.drawControlHandles(element) } /** * 绘制悬停状态 */ drawHover() { if (!this.hoveredElementId || !this.templateData || this.draggingElement) return const element = this.templateData.templateObjects.find(el => el.id === this.hoveredElementId) if (!element) return this.drawElementHighlight(element, '#67c23a', 1) } /** * 绘制元素高亮 */ drawElementHighlight(element, color, lineWidth) { const x = this.mmToPixel(element.left || 0) const y = this.mmToPixel(element.top || 0) const width = this.mmToPixel(element.width || 0) const height = this.mmToPixel(element.height || 0) this.ctx.save() this.ctx.strokeStyle = color this.ctx.lineWidth = lineWidth this.ctx.setLineDash([5, 5]) this.ctx.strokeRect(x, y, width, height) this.ctx.restore() } /** * 绘制控制手柄 */ drawControlHandles(element) { const x = this.mmToPixel(element.left || 0) const y = this.mmToPixel(element.top || 0) const width = this.mmToPixel(element.width || 0) const height = this.mmToPixel(element.height || 0) const handleSize = 6 // 定义控制点位置 const handles = [ { x: x - handleSize/2, y: y - handleSize/2, type: 'nw' }, // 左上 { x: x + width/2 - handleSize/2, y: y - handleSize/2, type: 'n' }, // 上中 { x: x + width - handleSize/2, y: y - handleSize/2, type: 'ne' }, // 右上 { x: x - handleSize/2, y: y + height/2 - handleSize/2, type: 'w' }, // 左中 { x: x + width - handleSize/2, y: y + height/2 - handleSize/2, type: 'e' }, // 右中 { x: x - handleSize/2, y: y + height - handleSize/2, type: 'sw' }, // 左下 { x: x + width/2 - handleSize/2, y: y + height - handleSize/2, type: 's' }, // 下中 { x: x + width - handleSize/2, y: y + height - handleSize/2, type: 'se' } // 右下 ] // 绘制控制点 handles.forEach(handle => { this.ctx.fillStyle = '#ffffff' this.ctx.fillRect(handle.x + this.offsetX, handle.y + this.offsetY, handleSize, handleSize) this.ctx.strokeStyle = '#409eff' this.ctx.lineWidth = 1 this.ctx.strokeRect(handle.x + this.offsetX, handle.y + this.offsetY, handleSize, handleSize) }) } /** * 绘制边界 */ drawBounds() { this.ctx.save() this.ctx.strokeStyle = '#e0e0e0' this.ctx.lineWidth = 1 this.ctx.setLineDash([2, 2]) this.ctx.strokeRect( this.bounds.minX, this.bounds.minY, this.bounds.maxX - this.bounds.minX, this.bounds.maxY - this.bounds.minY ) this.ctx.restore() } /** * 事件处理:画布点击 */ handleCanvasClick(event) { if (!this.templateData) return const rect = this.canvas.getBoundingClientRect() const x = event.clientX - rect.left - this.offsetX const y = event.clientY - rect.top - this.offsetY // 查找点击的元素 const clickedElement = this.findElementAtPoint(x, y) if (clickedElement) { // 选择元素 this.selectedElementId = clickedElement.id // 更新 Store if (this.templateData.SELECT_ELEMENT) { this.templateData.SELECT_ELEMENT(clickedElement.id) } // 触发选择事件 this.emit('select', clickedElement) } else { // 点击空白处,清除选择 this.selectedElementId = null if (this.templateData.CLEAR_SELECTION) { this.templateData.CLEAR_SELECTION() } } this.scheduleRender() } /** * 事件处理:鼠标移动 */ handleMouseMove(event) { if (!this.templateData) return const rect = this.canvas.getBoundingClientRect() const x = event.clientX - rect.left - this.offsetX const y = event.clientY - rect.top - this.offsetY // 拖拽处理 if (this.draggingElement) { this.handleDragMove(x, y) return } // 悬停处理 const hoveredElement = this.findElementAtPoint(x, y) if (hoveredElement && hoveredElement.id !== this.hoveredElementId) { this.hoveredElementId = hoveredElement.id this.canvas.style.cursor = 'move' this.scheduleRender() } else if (!hoveredElement && this.hoveredElementId) { this.hoveredElementId = null this.canvas.style.cursor = 'default' this.scheduleRender() } } /** * 事件处理:鼠标按下 */ handleMouseDown(event) { if (!this.templateData || !this.selectedElementId) return const rect = this.canvas.getBoundingClientRect() const x = event.clientX - rect.left - this.offsetX const y = event.clientY - rect.top - this.offsetY // 检查是否点击了选中的元素 const element = this.templateData.templateObjects.find(el => el.id === this.selectedElementId) if (!element) return const elementX = this.mmToPixel(element.left || 0) const elementY = this.mmToPixel(element.top || 0) const elementWidth = this.mmToPixel(element.width || 0) const elementHeight = this.mmToPixel(element.height || 0) // 判断是否点击在元素范围内 if (x >= elementX && x <= elementX + elementWidth && y >= elementY && y <= elementY + elementHeight) { this.startDragging(element, x, y) } } /** * 开始拖拽 */ startDragging(element, startX, startY) { this.draggingElement = element this.dragStartPos = { x: startX, y: startY } this.dragElementStartPos = { x: element.left || 0, y: element.top || 0 } this.canvas.style.cursor = 'grabbing' } /** * 处理拖拽移动 */ handleDragMove(x, y) { if (!this.draggingElement || !this.templateData) return // 计算移动距离(毫米) const deltaX = this.pixelToMm(x - this.dragStartPos.x) const deltaY = this.pixelToMm(y - this.dragStartPos.y) // 计算新位置(对齐到网格) const gridSize = this.config.gridSize let newLeft = Math.round((this.dragElementStartPos.x + deltaX) / gridSize) * gridSize let newTop = Math.round((this.dragElementStartPos.y + deltaY) / gridSize) * gridSize // 边界检查 const page = this.templateData.templateObjects.find(el => el.name === 'page') if (page) { const maxX = page.width - (this.draggingElement.width || 0) const maxY = page.height - (this.draggingElement.height || 0) newLeft = Math.max(0, Math.min(newLeft, maxX)) newTop = Math.max(0, Math.min(newTop, maxY)) } // 更新元素位置 if (this.templateData.UPDATE_ELEMENT) { this.templateData.UPDATE_ELEMENT({ id: this.draggingElement.id, attributes: { left: newLeft, top: newTop } }) } this.scheduleRender() } /** * 事件处理:鼠标松开 */ handleMouseUp() { if (this.draggingElement) { this.draggingElement = null this.canvas.style.cursor = 'move' // 触发更新事件 this.emit('update', { type: 'dragEnd' }) } } /** * 事件处理:鼠标离开 */ handleMouseLeave() { if (this.hoveredElementId) { this.hoveredElementId = null this.scheduleRender() } } /** * 事件处理:键盘按下 */ handleKeyDown(event) { if (!this.selectedElementId || !this.templateData) return // 删除键 if (event.key === 'Delete' || event.key === 'Backspace') { event.preventDefault() if (this.templateData.DELETE_ELEMENT) { this.templateData.DELETE_ELEMENT(this.selectedElementId) this.selectedElementId = null this.scheduleRender() } } // 方向键移动 const moveStep = 1 // 1mm let deltaX = 0, deltaY = 0 switch (event.key) { case 'ArrowUp': deltaY = -moveStep break case 'ArrowDown': deltaY = moveStep break case 'ArrowLeft': deltaX = -moveStep break case 'ArrowRight': deltaX = moveStep break } if (deltaX !== 0 || deltaY !== 0) { event.preventDefault() const element = this.templateData.templateObjects.find(el => el.id === this.selectedElementId) if (element && this.templateData.UPDATE_ELEMENT) { const newLeft = (element.left || 0) + deltaX const newTop = (element.top || 0) + deltaY this.templateData.UPDATE_ELEMENT({ id: element.id, attributes: { left: newLeft, top: newTop } }) this.scheduleRender() } } } /** * 事件处理:窗口大小变化 */ handleResize() { this.updateCanvasSize() } /** * 查找指定坐标下的元素 */ findElementAtPoint(x, y) { if (!this.templateData?.templateObjects) return null // 反向遍历(后绘制的元素在上层) const elements = [...this.templateData.templateObjects].reverse() for (const element of elements) { if (element.name === 'page') continue const elementX = this.mmToPixel(element.left || 0) const elementY = this.mmToPixel(element.top || 0) const elementWidth = this.mmToPixel(element.width || 0) const elementHeight = this.mmToPixel(element.height || 0) if (x >= elementX && x <= elementX + elementWidth && y >= elementY && y <= elementY + elementHeight) { return element } } return null } /** * 毫米转像素 */ mmToPixel(mm) { if (this.mmToPixelCache[mm] !== undefined) { return this.mmToPixelCache[mm] } const pixels = (mm * this.config.dpi) / 25.4 * this.config.scale this.mmToPixelCache[mm] = pixels return pixels } /** * 像素转毫米 */ pixelToMm(pixel) { return (pixel * 25.4) / (this.config.dpi * this.config.scale) } /** * 解析样式字符串 */ parseStyle(styleString) { if (!styleString) return {} const style = {} const pairs = styleString.split(';').filter(Boolean) pairs.forEach(pair => { const [key, value] = pair.split(':').map(s => s.trim()) if (key && value) { style[key] = value } }) return style } /** * 截断文本 */ truncateText(text, maxWidth) { let truncated = text const ellipsis = '...' while (this.ctx.measureText(truncated + ellipsis).width > maxWidth && truncated.length > 1) { truncated = truncated.slice(0, -1) } return truncated + ellipsis } /** * 事件发射 */ on(event, callback) { if (!this.eventListeners[event]) { this.eventListeners[event] = [] } this.eventListeners[event].push(callback) } /** * 事件触发 */ emit(event, data) { if (this.eventListeners[event]) { this.eventListeners[event].forEach(callback => { callback(data) }) } } /** * 销毁 */ destroy() { this.removeEventListeners() this.templateData = null this.canvas = null this.ctx = null this.container = null console.log('CanvasRenderer 已销毁') } } export default CanvasRenderer