1. 程式人生 > 實用技巧 >canvas例項--手寫簽名

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>