美文网首页
canvas实现简易的画画板

canvas实现简易的画画板

作者: 无敌万小奔 | 来源:发表于2017-06-01 16:10 被阅读0次

    html样式

    <head>
        <meta charset="UTF-8" />
        <title>Document</title>
        <style type="text/css">
            canvas {
                border: 1px solid #ccc;
            }
        </style>
    </head>
    <body>
        <input id="colorSelect" type="color" name="" value="" placeholder="">
        <br>
        <input type="submit" name="" value="清空画板" onclick="qingkong()">
        <br>
        <canvas width="500" height="500" id="canvas">
            您的浏览器不支持
        </canvas>
    </body>
    

    javascript代码

    //  获取Input的id
        var selector = document.getElementById("colorSelect");
        // 声明color的全局变量
        var color = null;
        // 获取color的颜色
        selector.onchange = function(){
            color = this.value;
        }
        var canvas = document.getElementById("canvas");
        var cxt = canvas.getContext("2d");
        // 鼠标按下
        canvas.onmousedown = function(e){
            // 获取canvas画面上的x y 轴
            var x = e.clientX - canvas.offsetLeft;
            var y = e.clientY - canvas.offsetTop;
            cxt.beginPath();
            cxt.moveTo(x,y);
            canvas.onmousemove = function(e){
                var x = e.clientX - canvas.offsetLeft;
                var y = e.clientY - canvas.offsetTop;
                cxt.lineTo(x,y);
                cxt.strokeStyle=color;
                cxt.stroke();
            }
            // 鼠标抬起事件 把上一个的move的事件清空
            canvas.onmouseup = function(){
                canvas.onmousemove = null;
            }
        }
        // 一键清空按钮
        function qingkong(){
            cxt.clearRect(0,0,500,500);
            console.log(11);
        }
    

    相关文章

      网友评论

          本文标题:canvas实现简易的画画板

          本文链接:https://www.haomeiwen.com/subject/syjefxtx.html