这篇文章主要介绍了关于vue利用canvas实现移动端手写板的方法,有着一定的参考价值,现在分享给大家,有需要的朋友可以参考一下
本文介绍了vue利用canvas实现移动端手写板的方法,分享给大家,具体如下:
<template>
<p 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="">
</p>
</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>
相关推荐:
vue在页面右上角实现可悬浮/隐藏的系统菜单
vue裁切预览组件功能的实现步骤
以上就是vue利用canvas实现移动端手写板的方法的详细内容。