canvas移动端实现画板批改功能

说明: 最近有图片批改作业主观题的需求,所以研究了一下canvas实现了移动端
功能:放大 缩小 批改 橡皮檫 清空 保存图片
这里就不说明实现过成了详情请见pc端的实现思路 //www.greatytc.com/p/8811c715330e
这里直接上代码了

<template>
<div class="awe" id="awe" style="width: 100px; height: 100px" >
    <div class="botton">
        <button class="enlarge" @click="enlargeClick">+</button>
        <button class="enlarge" @click="emptyTheCanvas">-</button>
        <button class="enlarge" @click="rubber">橡皮</button>
        <button class="enlarge" @click="brush">画笔</button>
        <button class="enlarge" @click="baocun">保存</button>
        <button class="enlarge" @click="qingkong">清空</button>
    </div>
    <div class="canvas" >
        <canvas class="canvasas" id="drawing-board"  @touchstart.stop.prevent="onmousedown" @touchmove.stop.prevent="onmousemove" @touchend.stop.prevent="onmouseup" ></canvas>
        <canvas id="drawing-board1"></canvas>
    </div>
</div>
</template>
<script>
export default {
data () {
    return {
        myPaint: false,
        myClickX: [],
        myClickY: [],
        myClickDrag: [],
        myContext: null,
        canvas: null,
        image: null,
        myContextRce: null,
        canvasRce: null,
        img: null,
        rubberShow: false,
        rubberShow1: false,
        url1: '',
        res: '',
        swer: false
    }
},
methods: {
    // 定义画布对象  画布显示二维图片
    canvas1() {
        this.myContext = document.getElementById('drawing-board').getContext('2d');
        this.canvas = document.getElementById('drawing-board')
        this.myContextRce = document.getElementById('drawing-board1').getContext('2d');
        this.canvasRce = document.getElementById('drawing-board1')
    },
    // 禁止滚轮放大缩小图片
    mousewheel() {
        window.addEventListener('mousewheel', function (event) {
            if (event.ctrlKey === true || event.metaKey) {
                event.preventDefault();
            }
        }, { passive: false });
    },
    initialization1 () {
        // 将图片放到画布里面 myContext.drawImage(img, 0, 0)
        this.img = new Image()//创建一个image对象 通过构造函数创建 img 实例
        this.img.src =  "https://dss2.bdstatic.com/70cFvnSh_Q1YnxGkpoWK1HF6hhy/it/u=3228549874,2173006364&fm=26&gp=0.jpg";
        this.img.setAttribute("crossOrigin",'Anonymous')//  解决图片跨域问题
        this.canvasRce.width = this.img.width;
        this.canvasRce.height = this.img.height;
        this.img.onload =  (e) => { // 确保图片完整获取到,创建一个异步事件
            this.drawImage1();
        };
    },
    drawImage1(sec = 1) {
        this.canvasRce.width = this.img.width * (sec == 1 ? 0.5 : sec);
        this.canvasRce.height = this.img.height * (sec == 1 ? 0.5 : sec);
        this.img.width = this.img.width * (sec == 1 ? 0.5 : sec);
        this.img.height = this.img.height * (sec == 1 ? 0.5 : sec);
        this.myContextRce.drawImage(this.img,0,0,this.img.width, this.img.height);
    },

    // 定义一个image对象并设置好它的onload事件和src属性。
    initialization () {
        // 将图片放到画布里面 myContext.drawImage(img, 0, 0)
        this.image = new Image()//创建一个image对象 通过构造函数创建 img 实例
        this.image.src = "https://dss2.bdstatic.com/70cFvnSh_Q1YnxGkpoWK1HF6hhy/it/u=3228549874,2173006364&fm=26&gp=0.jpg";
        this.image.setAttribute("crossOrigin",'Anonymous')//  解决图片跨域问题
        this.image.onload =  (e) => { // 确保图片完整获取到,创建一个异步事件
            this.drawImage();
        };
    },
    drawImage(sec = 1) {
        this.myContext.clearRect(0, 0, this.canvas.width, this.canvas.height); // 清空画版
        this.canvas.width = this.image.width * (sec == 1 ? (this.swer == true ? 1 : 0.5)  : sec)
        this.canvas.height = this.image.height * (sec == 1 ? (this.swer == true ? 1 : 0.5)  : sec)
        this.image.width = this.image.width * (sec == 1 ? (this.swer == true ? 1 : 0.5)  : sec)
        this.image.height = this.image.height * (sec == 1 ? (this.swer == true ? 1 : 0.5)  : sec)
        this.myContext.drawImage(this.image,0,0,this.image.width, this.image.height);
        this.swer = false
    },
    // 在图片上做画根据鼠标移动轨迹
    redraw(){
        this.myContext.strokeStyle = '#f00'; // 设置颜色
        this.myContext.lineJoin = 'round';
        this.myContext.lineWidth = 5; //设置粗细
        for(let i=0;i<this.myClickX.length;i++){
            this.myContext.beginPath();
            if(this.myClickDrag[i] && i){
                this.myContext.moveTo(this.myClickX[i-1], this.myClickY[i-1])
            }else{
                this.myContext.moveTo(this.myClickX[i]-1,this.myClickY[i])
            }
            this.myContext.lineTo(this.myClickX[i],this.myClickY[i]);
            this.myContext.closePath();
            this.myContext.stroke();
        }
    },
    // 将鼠标移动的轨迹放到myClickDrag 数组中
    addClick(x,y,dragging){
        this.myClickX.push(x);
        this.myClickY.push(y);
        this.myClickDrag.push(dragging);
    },
    // 鼠标按下事件
    onmousedown(e) {
        console.log(e.targetTouches[0].clientX,"pageX")
        if(this.rubberShow){
            this.rubberShow1 = true
            return false
        }
        this.myPaint = true
        this.addClick(e.targetTouches[0].clientX-this.canvas.offsetLeft, e.targetTouches[0].clientY - this.canvas.offsetTop);
        if(this.myPaint){
            this.redraw();
        }
    },
    // 鼠标移动事件
    onmousemove(e) {
        if(this.myPaint){
            this.addClick(e.targetTouches[0].clientX-this.canvas.offsetLeft,e.targetTouches[0].clientY - this.canvas.offsetTop,true);
            this.redraw();
        }
        if(this.rubberShow1){
            this.myContext.clearRect(e.targetTouches[0].clientX-this.canvas.offsetLeft,e.targetTouches[0].clientY - this.canvas.offsetTop,10,10);
        }
    },
    // 鼠标抬起事件
    onmouseup() {
        this.swer = true
        this.myPaint = false;
        this.rubberShow1 = false
        this.image.src = this.canvas.toDataURL("image/png");
        this.myClickX = new Array();
        this.myClickY = new Array();
        this.myClickDrag = new Array();
    },
    // 鼠标移除canvas画布
    onmouseout() {
        this.myPaint = false;
    },
    // 画布放大
    enlargeClick () {
        this.drawImage(1.2)
        this.drawImage1(1.2)
    },
    // 画布缩小
    emptyTheCanvas() {
        this.drawImage(0.8)
        this.drawImage1(0.8)
    },
    // 橡皮檫
    rubber() {
        this.rubberShow = true
        this.myPaint = false
    },
    brush () {
        this.rubberShow = false
    },
    // 保存
    baocun() {
        let imgtext = new Image()
        imgtext.src = this.img.src
        imgtext.setAttribute("crossOrigin",'Anonymous')//  解决图片跨域问题
        imgtext.onload = (e) => {
            this.myContext.drawImage(imgtext,0,0,this.image.width, this.image.height);
            let imgtext1 = new Image()
            imgtext1.src = this.image.src
            imgtext1.setAttribute("crossOrigin",'Anonymous')//  解决图片跨域问题
            imgtext1.onload = (e) => {
                this.myContext.drawImage(imgtext1,0,0,this.image.width, this.image.height);
                this.url1 = this.canvas.toDataURL("image/png"); //"image/png" 这里注意一下
                var a = document.createElement('a');          // 创建一个a节点插入的document
                var event = new MouseEvent('click')           // 模拟鼠标click点击事件
                a.download = '图片名字'                  // 设置a节点的download属性值
                a.href = this.url1;                                 // 将图片的src赋值给a节点的href
                a.dispatchEvent(event)      
            }
        }
    },
    // 清空
    qingkong () {
        this.myContext.clearRect(0,0,this.image.width, this.image.height)
        this.myClickX = new Array();
        this.myClickY = new Array();
        this.myClickDrag = new Array();
    }
},   

async mounted () {
    await this.canvas1()
    await this.initialization() 
    await this.initialization1() 
    this.mousewheel()
}
}
</script>

<style lang="less">
.awe{
    width: 100vw !important;
    height: 100vh !important;
    display: flex;
    position: relative;
    .botton{
        height: 100%;
        position: absolute;
        z-index: 1000;
    }
    .enlarge{
        width: 40px;
        height: 40px;
        font-size: 10px;
        display: flex;
        align-items: center;
        justify-content: center;
    }
    .canvas{
        display: flex;
        width: 100%;
        justify-content: center;
        align-items: center;
        .canvasas{
            position: absolute;
        }
    }
}
    
</style>
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 215,245评论 6 497
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 91,749评论 3 391
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 160,960评论 0 350
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 57,575评论 1 288
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 66,668评论 6 388
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 50,670评论 1 294
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,664评论 3 415
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,422评论 0 270
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,864评论 1 307
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,178评论 2 331
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,340评论 1 344
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,015评论 5 340
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 40,646评论 3 323
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,265评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,494评论 1 268
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,261评论 2 368
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,206评论 2 352

推荐阅读更多精彩内容