zoukankan      html  css  js  c++  java
  • canvas简易画板。

    在学canvas的时候,想到可以做一个自己用来画画的简易画板,加上canvas的基础都已经学完,便尝试做了一个画板。如图

    1.获取标签.

        var c=document.getElementById('myCanvas');
        var ctx= c.getContext('2d');var b=document.getElementById('b');
        var b1=document.getElementById('b1');
        var bbb=document.getElementById('bbb');
        var col=document.getElementById('col');

    c为canvas画板,ctx为定义canvas需要的属性,b为铅笔的粗细,b1为橡皮擦的大小,bbb为手动设置的铅笔大小,col为调色板。

    2.设置画板组件

    b.onmousedown=function(){
    document.onmousemove=function(){
    bbb.value=b.value;
    }
    }
    b1.onmousedown=function(){
    document.onmousemove=function(){
    }
    }
    
    bbb.onblur=function(){
    b.value=bbb.value;
    }
    bbb.onkeydown=function(e){
    if(e.keyCode==13){
    b.value=bbb.value;
    }
    }

    这几个绑定事件都是给画板组件添加的事件,例如铅笔粗细,onkeydown为手动设置铅笔粗细时可直接点击回车键确定。

    3.设置铅笔

    pencil.onclick=function(){
    c.onmousedown=function(e){
    var e=e||event;
    var x= e.clientX- c.offsetLeft;
    var y= e.clientY- c.offsetTop;
    ctx.beginPath();
    ctx.moveTo(x,y);
    document.onmousemove=function(e){
    
    var e=e||event;
    var x1= e.clientX- c.offsetLeft;
    var y1= e.clientY- c.offsetTop;
    ctx.strokeStyle=col.value;
    ctx.lineTo(x1,y1);
    ctx.lineWidth=b.value;
    ctx.stroke();
    
    };
    };
    }

    要将画的画显示在页面上,首先需要到canvas的moveto和lineto属性,然后需要将两个属性的坐标分别绑定在onmousedown事件上和onmousemove事件上,一个为鼠标按下时获取的坐标,然后移动的时候用onmousemove获取到鼠标移动时的坐标,久可以将图显示在画布上。

    4.设置橡皮擦

    eraser.onclick=function(){
    c.onmousedown=function(e){
    var e=e||event;
    var x= e.clientX- c.offsetLeft;
    var y= e.clientY- c.offsetTop;
    ctx.beginPath();
    ctx.moveTo(x,y);
    document.onmousemove=function(e){
    var e=e||event;
    var x1= e.clientX- c.offsetLeft;
    var y1= e.clientY- c.offsetTop;
    ctx.strokeStyle='gray';
    ctx.lineTo(x1,y1);
    ctx.lineWidth=b1.value;
    ctx.stroke();
    
    };
    };
    }

    橡皮擦其实原理和铅笔一模一样,只是将颜色换为背景色即可。

    5.取消绑定

    window.onmouseup=function(){
    
    document.onmousedown=null;
    document.onmousemove=null;
    }

    在放开鼠标时,用onmouseup事件将绑定的事件移除(js取消绑定事件用null,jquery用unbind)

    6,.将图片下载

    var but=document.getElementById('but');
    
    but.onclick=function(){
    var str=load(c);
    document.getElementById('hre').href=str;
    }
    
    function load(canvas){
    var load=canvas.toDataURL("image/png");
    return load;
    }

    todataurl是将绘制的图案转化为base64格式的编码。然后在将base64编码转化为图片,最后将base64放在a标签里的href里,即可以点击完成下载。

  • 相关阅读:
    阿里云如何打破Oracle迁移上云的壁垒
    第三代DRDS分布式SQL引擎全新发布
    玩转MaxCompute studio SQL编辑器
    如何在阿里云上安全的存放您的配置
    阿里云E-HPC联合安世亚太、联科集团共建云超算生态
    阿里云弹性裸金属服务器-神龙架构(X-Dragon)揭秘
    从保障淘宝到全球市场“第一阵营”,阿里云的DDoS防护之路走了多远?
    飞天技术汇“2018云栖大会·上海峰会”专场,等你加入
    Yeoman:Web 应用开发流程与工具—AngularJS—Bootstrap—js
    【codeforces 550A】Two Substrings
  • 原文地址:https://www.cnblogs.com/zh23/p/7096433.html
Copyright © 2011-2022 走看看