canvas实例--手写签名

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        *{
            margin:0;
            padding:0;
        }
        body,html{
            height:100%;
            overflow: hidden;
            background: #616161;
        }
        #test{
            position: absolute;
            left:50%;
            top:50%;
            transform: translate3d(-50%,-50%,0);
            background: white;
            margin:auto;
        }
    </style>
</head>
<body>
<canvas id="test">
    <span>您的浏览器不支持canvas操作!!</span>
</canvas>
</body>
</html>
<script>
    var canvas=document.querySelector('#test');
    if(canvas.getContext){
        var ctx=canvas.getContext("2d");}
        canvas.onmousedown=function (ev) {
        ev=ev||window.event;
        if(canvas.setCapture){
            canvas.setCapture();}
            ctx.save();  //在栈里添加黑色
            ctx.strokeStyle='pink';   //将样式改成粉色
            // ctx.lineWidth=10;
            ctx.beginPath();  ctx.moveTo(ev.clientX-canvas.offsetLeft,ev.clientY-canvas.offsetLeft);
            //鼠标移动时发生
            document.onmousemove=function (ev) {
            ev=ev||window.event;
            ctx.lineTo(ev.clientX-canvas.offsetLeft,ev.clientY-canvas.offsetLeft);
            ctx.stroke();
            ctx.restore();};
            document.onmouseup=function () {
                document.onmousemove=document.onmouseup=null;
                    if(document.releaseCapture){
                        document.releaseCapture();}};
            // ctx.restore();
    return false;}
</script>
posted @ 2020-08-19 15:00  花未眠0619  阅读(237)  评论(0)    收藏  举报