h5 Canvas实现签名写字

17 篇文章 0 订阅

Canvas元素是HTML5比较受欢迎的功能,这个元素负责在页面中设定一个区域,然后就可以通过JavaScript动态在这个区域绘制图形。

canvas 宽高不能使用样式设置,这个画布的宽高,必须使用html标签来设置

<canvas width="800" height="600"></canvas>
canvas{
         background-color: oldlace;
        }

获取canvas var canvas=document.querySelector("canvas");
获取这个元素的context——图像稍后将在此被渲染。
获取canvas上下文环境 var ctx=canvas.getContext("2d");
开始绘制路径 ctx.beginPath();
从哪一个点开始 ctx.moveTo(20,20);
绘制笔触线条到什么位置 ctx.lineTo(150,50);
通过线条绘制图形轮廓 ctx.stroke();
线条颜色 ctx.strokeStyle="red";
线条宽度 ctx.lineWidth=3;
线条线段端点样式 ctx.lineCap="round";
两线段连接处所显示的样子 ctx.lineJoin="round;"

lineCap有butt、round、square三种样式
在这里插入图片描述
lineJoin有round、bevel、miter(默认)三种样式
在这里插入图片描述
代码部分

<!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>
        body{
            background-color: beige;
        }
        canvas{
            background-color: white;
            margin: auto;
            position: absolute;
            left: 0;
            right: 0;
        }
    </style>
</head>
<body>
    <canvas width="800" height="600"></canvas>
    <script>
        var canvas=document.querySelector("canvas");
        var ctx=canvas.getContext("2d");
        canvas.addEventListener("mousedown",mouseHandler);
        ctx.lineCap="round";
        ctx.lineJoin="round";
        ctx.strokeStyle="red";
        ctx.lineWidth=3;
        function mouseHandler(e){
            if(e.type==="mousedown"){
                ctx.moveTo(e.offsetX,e.offsetY);
                canvas.addEventListener("mousemove",mouseHandler);
                canvas.addEventListener("mouseup",mouseHandler);
            }else if(e.type==="mousemove"){
                ctx.lineTo(e.offsetX,e.offsetY);
            }else if(e.type==="mouseup"){
                canvas.removeEventListener("mousemove",mouseHandler);
                canvas.removeEventListener("mouseup",mouseHandler);
            }
            ctx.stroke();
        }
    </script>
    
</body>
</html>

效果图
在这里插入图片描述

  • 7
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值