使用canvas可以做到许多意想不到的功能,尤其动画方面,这次在vue项目中使用canvas制作一个简易涂鸦板
1. html部分代码
<template> <div id="app-box"> <!-- 画布 --> <canvas id="canvas-box" ref="box"></canvas> <!-- 功能 --> <div class="input-line"> <div class="color-select"> <input type="color" id="color-box" @change="selectColor" ref="colorBox" v-model="colorValue" > <label for="color-box">选择画笔颜色</label> </div> <div class="number-select"> <input type="number" id="number-box" v-model="numberValue" min="1" max="8" @change="selectNumber" > <label for="number-box">选择画笔粗细</label> </div> <button @click="clearCanvas">清空屏幕</button> </div> </div> </template>
上面主要由一个画布区域和下面的操作栏按钮实现
2. css部分代码
<style> .input-line{ width: 500px; display: flex; justify-content: space-between; margin-top: 10px; } .color-select, .number-select{ width: 200px; } #number-box{ width: 50px; } </style>
画布的大小是由canvas控制的,这里设置的是下面按钮的排列
3.JS部分代码
<script> export default { name:'App', data() { return { colorValue:'#000000', numberValue:1 } }, methods: { //清空画布 clearCanvas(){ this.$refs.box.getContext('2d').clearRect(0, 0, 500, 500); console.log('清空'); }, //设置画笔颜色 selectColor(){ this.$refs.box.getContext('2d').strokeStyle = this.colorValue console.log('选择颜色',this.colorValue); }, //设置画笔的粗细 selectNumber(){ this.$refs.box.getContext('2d').lineWidth = this.numberValue console.log('选择粗细',this.numberValue); } }, mounted() { //获取画布对象 let box = this.$refs.box //准备画笔 let boxText = box.getContext('2d'); //设置画布大小 box.width = 500 box.height = 500 box.style.border = "1px solid #000"; //设置画笔颜色 boxText.strokeStyle = this.$refs.colorBox.value //设置画布事件 box.onmousedown = (e)=>{ let x = e.clientX - box.getBoundingClientRect().left; let y = e.clientY - box.getBoundingClientRect().top; boxText.beginPath();//开始规划路径 boxText.moveTo(x, y);//移动起始点 //当鼠标移动触发onmousemove事件时,定义一个函数获取绘制线条的坐标 box.onmousemove = (event)=> { let x = event.clientX- box.getBoundingClientRect().left; let y = event.clientY- box.getBoundingClientRect().top; boxText.lineTo(x, y);//绘制线条 boxText.stroke();//绘制描边 }; //当鼠标按键被松开时,onmousemovet函数返回null box.onmouseup = ()=> { box.onmousemove = null; }; } }, } </script>