<el-dialog title="签字板" v-model="visible" width="1000px" append-to-body> <canvas @mousemove="canvasMove" @mouseup="canvasUp" ref="canvas" width="1000" height="500" @mousedown="mousedown" @mouseleave="canvasLeave"></canvas> <template #footer> <div class="dialog-footer"> <el-button type="primary" @click="handleSave">保 存</el-button> <el-button @click="handleClear">重 置</el-button> </div> </template> </el-dialog>
<script setup> const visible = ref(false) const isDown = ref(false) // 是否可以绘制 const canvas = ref(null) // canvas 元素 const ctx = ref(null) // ctx承接上下文 // 鼠标按下 function mousedown (e) { let { offsetX, offsetY } = e // 拿到x,y坐标 ctx.value = canvas.value.getContext('2d') // 上下文 // console.log(ctx.value) ctx.value.strokeStyle = '#000'; // 设置线条颜色 ctx.value.fillStyle = '#fff' ctx.value.lineWidth = 5; // 线条宽度 ctx.value.beginPath(); // 开始绘制路径 ctx.value.moveTo(offsetX, offsetY); // 将鼠标移动到某一个坐标,准备绘制 isDown.value = true // 打开绘制开关 } // 鼠标移动 function canvasMove (e) { let { offsetX, offsetY } = e // 拿到移动时的坐标信息 isDown.value && startDraw(offsetX, offsetY) // 绘制开关为true 开始绘制 } // 鼠标松开 function canvasUp() { console.log('松开'); isDown.value = false } // 鼠标超出canvas绘制区域 function canvasLeave() { console.log('超出canvas'); isDown.value = false } // 绘制方法 function startDraw(x, y) { ctx.value.lineTo(x, y); // 绘制线条 ctx.value.stroke(); // } function handleClear() { ctx.value.clearRect(0, 0, 1000, 500) } function handleSave() { const base64 = canvas.value.toDataURL() console.log(base64) // 输出base64的图片地址 } </script>
标签:function,canvas,const,ctx,value,vue3,重签,绘制 From: https://www.cnblogs.com/ai01/p/17997080