Vue利用canvas实现移动端手写板的方法
程序员文章站
2022-04-10 11:39:18
本文介绍了vue利用canvas实现移动端手写板的方法,分享给大家,具体如下:
本文介绍了vue利用canvas实现移动端手写板的方法,分享给大家,具体如下:
<template> <div class="hello"> <!--touchstart,touchmove,touchend,touchcancel 这--> <button type="" v-on:click="clear">清除</button> <button v-on:click="save">保存</button> <canvas id="canvas" width="300" height="600" style="border:1px solid black">canvas画板</canvas> <img v-bind:src="url" alt=""> </div> </template> <script> var draw; var prehandler = function(e){e.preventdefault();} class draw { constructor(el) { this.el = el this.canvas = document.getelementbyid(this.el) this.cxt = this.canvas.getcontext('2d') this.stage_info = canvas.getboundingclientrect() this.path = { beginx: 0, beginy: 0, endx: 0, endy: 0 } } init(btn) { var that = this; this.canvas.addeventlistener('touchstart', function(event) { document.addeventlistener('touchstart', prehandler, false); that.drawbegin(event) }) this.canvas.addeventlistener('touchend', function(event) { document.addeventlistener('touchend', prehandler, false); that.drawend() }) this.clear(btn) } drawbegin(e) { var that = this; window.getselection() ? window.getselection().removeallranges() : document.selection.empty() this.cxt.strokestyle = "#000" this.cxt.beginpath() this.cxt.moveto( e.changedtouches[0].clientx - this.stage_info.left, e.changedtouches[0].clienty - this.stage_info.top ) this.path.beginx = e.changedtouches[0].clientx - this.stage_info.left this.path.beginy = e.changedtouches[0].clienty - this.stage_info.top canvas.addeventlistener("touchmove",function(){ that.drawing(event) }) } drawing(e) { this.cxt.lineto( e.changedtouches[0].clientx - this.stage_info.left, e.changedtouches[0].clienty - this.stage_info.top ) this.path.endx = e.changedtouches[0].clientx - this.stage_info.left this.path.endy = e.changedtouches[0].clienty - this.stage_info.top this.cxt.stroke() } drawend() { document.removeeventlistener('touchstart', prehandler, false); document.removeeventlistener('touchend', prehandler, false); document.removeeventlistener('touchmove', prehandler, false); //canvas.ontouchmove = canvas.ontouchend = null } clear(btn) { this.cxt.clearrect(0, 0, 300, 600) } save(){ return canvas.todataurl("image/png") } } export default { data () { return { msg: 'welcome to your vue.js app', val:true, url:"" } }, mounted() { draw=new draw('canvas'); draw.init(); }, methods:{ clear:function(){ draw.clear(); }, save:function(){ var data=draw.save(); this.url = data; console.log(data) }, mutate(word) { this.$emit("input", word); }, } } </script> <!-- add "scoped" attribute to limit css to this component only --> <style scoped> h1, h2 { font-weight: normal; } ul { list-style-type: none; padding: 0; } li { display: inline-block; margin: 0 10px; } a { color: #42b983; } #canvas { background: pink; cursor: default; } #keyword-box { margin: 10px 0; } </style>
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。