zoukankan      html  css  js  c++  java
  • 分享canvas的一个小案例

    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="UTF-8">
    <title></title>
    <style type="text/css">
    #cvs{
    margin: 50px;
    border: 1px solid #999999;
    }
    </style>
    </head>
    <body>
    <canvas id="cvs" width="500" height="400"></canvas>
    <button>画画</button>
    <button>清除</button>
    <button>重画</button>    
    </body>
    <script type="text/javascript">
    
    // 通过JavaScript使用document.getElementById()方法来确定正确的画布
    
    var cvs = document.getElementById("cvs")
    
    //每个画布都必须要有一个context(上下文)的定义
    var ctx = cvs.getContext("2d")
    
    //获取btn
    var btn=document.getElementsByTagName('button')
    
    //添加点击事件
    btn[0].onclick=function(){
    
    
    cvs.onmousedown=function(e){
    var Event=e||window.event
    
    //确定cvs的开始路径
    ctx.beginPath()
    ctx.moveTo(Event.clientX-cvs.offsetLeft,Event.clientY-cvs.offsetTop)
    
    document.onmousemove=function(e){
    var Event=e||window.event
    
    //路径移到画布中的指定点 , 即起点
    ctx.lineTo(Event.clientX-cvs.offsetLeft,Event.clientY-cvs.offsetTop)
    ctx.strokeStyle='blue'
    ctx.lineWidth=5;
    ctx.stroke()
    }
    
    document.onmouseup=function(){
    document.onmousedown=null
    document.onmousemove=null
    }
    
    }
    }
    
    //清除画布
    btn[1].onclick=function(){
    cvs.onmousedown=function(e){
    var Event=e||window.event
    document.onmousemove=function(e){
    var Event=e||window.event
    ctx.clearRect(Event.clientX-cvs.offsetLeft,Event.clientY-cvs.offsetTop,50,50)
    }
    document.onmouseup=function(){
    document.onmousedown=null
    document.onmousemove=null
    }
    
    }
    }
    
    //清除canvas
    btn[2].onclick=function(){
    ctx.clearRect(0,0,cvs.width,cvs.height)
    }
    </script>
    
    </html>
    越努力,越幸运
  • 相关阅读:
    [Leetcode] Flatten Binary Tree to Linked List
    [Leetcode] Letter Combinations of a Phone Number
    [Leetcode] Distinct Subsequences
    [Leetcode] Partition List
    [Leetcode] Reverse Linked List II
    [Leetcode] Swap Nodes in Pairs
    [Jobdu] 题目1391:顺时针打印矩阵
    [Jobdu] 题目1369:字符串的排列
    [Jobdu] 题目1283:第一个只出现一次的字符
    如何应用ML的建议-下
  • 原文地址:https://www.cnblogs.com/wyh243/p/7003358.html
Copyright © 2011-2022 走看看