利用canvas实现简易绘图版demo

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        #content{
            background:lightblue;
        }
    </style>
</head>
<body>
    <canvas id="content" width="500px" height="500px" background=""></canvas>
    <div class="tool">
        <button id="btn1">改变颜色</button>
        <button id="btn2">清空画布</button>
        <button id="btn3">使用橡皮擦</button>
        <button id="btn4">使用画笔</button>
    </div>
    
    <script>
        //获取容器创建画布、
        var content=document.querySelector("#content"),
        
       
        colorBtn=document.querySelector("button"),
        clearPage=document.querySelector("#btn2"),
        ecolor="lightblue"
        erBtn=document.querySelector("#btn3"),
        ctx=content.getContext('2d'),
        tag=false,
        tage=false;
 
        // 实现一个绘画板
        // 1.画布的样式设置
        
        //涉及到的事件有鼠标按下,鼠标移动,鼠标弹起
        content.addEventListener("mousedown",function(e){
           tag=true;
           ctx.beginPath();
           
        });
        content.addEventListener("mousemove",function(e){
            if(!tag) return;
            if(tag&&!tage){
              
                ctx.lineTo(e.clientX,e.clientY);
                ctx.stroke();
                
            }
            if(tage){
                ctx.beginPath();
                ctx.fillStyle=ecolor?ecolor:"white";
               ctx.arc(e.clientX,e.clientY,10,0,Math.PI*2);
               ctx.closePath();
               ctx.fill();

            }
            
           
        })
        content.addEventListener("mouseup",function(e){
            ctx.closePath();
            tag=false;
        });
        document.addEventListener("click",function(e){
            debugger
            var btn=e.target.getAttribute("id");
            switch(btn){
                case "btn1":
                ctx.strokeStyle="#"+Math.ceil(Math.random()*1000);
                break;
                case "btn2":
                ctx.clearRect(0,0,content.width,content.height);
                ctx.beginPath();
                break;
                case "btn3":
                tage=true;
                break;
                case "btn4":
                tage=false;
                break;
                default:
                break;
            }
        })
      

    </script>
</body>
</html>
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值