一个简单的canvas写字板、画板vue组件,因为项目需求目前只提供清空功能
代码及demojavascript
1.引入组件html
import draw from './inDraw/index'
components: { draw, },
2.使用组件,能够放在一个自定义样式的div中vue
<div id="draw-box"> <draw ref="in-draw" :inRatio="3" //retina屏兼容,画布大小放大倍数,Number :inLineColor="'#999'" //笔触颜色 :inLineWidth="5" //笔触宽度,Number :inShadowBlur="5" //笔触阴影大小,Number ></draw> <div class="draw-delete" @click="drawDelete()">清空</div> </div>
3.自定义清空按钮,调用组件方法inDeleteCanvas清空画布java
methods: { drawDelete(){ this.$refs["in-draw"].inDeleteCanvas() }, }
1.须要兼容retina屏一倍图模糊的问题,将画布大小设置为canvas元素的2或3倍git
//this.inRatio=3; let canvasDom=this.$refs['in-draw-canvas']; this.inCanvasBound = canvasDom.getBoundingClientRect(); canvasDom.width=this.inCanvasBound.width*this.inRatio; canvasDom.height=this.inCanvasBound.height*this.inRatio; this.inCtx.lineWidth=10*this.inRatio;
2.笔触锯齿问题,设置阴影github
this.inCtx.shadowBlur = 5; this.inCtx.shadowColor = "#000";
3.适应需求在不一样位置的画布,笔触实际位置为当前坐标减去画布位置canvas
let x=(e.changedTouches[0].pageX - this.inCanvasBound.left + 0.5)*this.inRatio; let y=(e.changedTouches[0].pageY- this.inCanvasBound.top + 0.5)*this.inRatio;