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里,即可以点击完成下载。

  • 相关阅读:
    技术的那些事儿_2_产品与工艺
    for与foreach再探讨
    技术的那些事儿_3_西方技术管理的精髓
    搭建免费的.Net开发环境
    CDN
    servu 系统服务看门狗,自动脱机补丁,自动启动
    .NET Remoting程序开发入门篇
    网管必知远程终端3389端口合理修改秘藉
    反射方法调用时的一个错误:参数计数不匹配( parameter count mismatch )
    VPS性能测试第一步:CPU测试
  • 原文地址:https://www.cnblogs.com/zh23/p/7096433.html
Copyright © 2011-2022 走看看