移动端的canvas电子签名

时间:2024-04-08 10:02:06

移动端的canvas电子签名效果,使用的是touch事件,pc端不支持

canvas设置的是手机端全屏宽高,可自己进行设置,手指滑动即可


代码:

<!DOCTYPE html>
<html>

<head>
<meta charset="UTF-8">
<title></title>
<meta name="viewport" content="device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" />
</head>
<styletype="text/css">
html,body{
/* 重置默认样式 */
margin: 0;
padding: 0;
}
html,body,#mycanvas{
width: 100%;
height: 100%;
overflow: hidden;
}
</style>
<body>
<div id="mycanvas">
<canvasid="canvas"></canvas>
</div>
<script>
/** 侦听touchstart事件 **/
document.body.addEventListener('touchstart',function(){
event.preventDefault();//手指滑动时,浏览器会上下左右翻屏
});
var oCanvas =document.getElementById("canvas");
oCanvas.width =document.body.clientWidth;
oCanvas.height =document.body.clientHeight;
var cxt =oCanvas.getContext("2d");
cxt.lineWidth =2;
var posX =0;//x坐标
var posY =0;//y坐标
var position =null;

//手指触摸屏幕可记录此时的位置作为起点
oCanvas.addEventListener("touchstart",function(){
posX = event.changedTouches[0].clientX;
posY = event.changedTouches[0].clientY;

cxt.moveTo(posX,posY);
});

//手指屏滑动画线
oCanvas.addEventListener("touchmove",function(){
posX = event.changedTouches[0].clientX;
posY = event.changedTouches[0].clientY;
cxt.lineTo(posX,posY);
cxt.stroke();
});

</script>

</body>

</html>


效果图:

移动端的canvas电子签名