38 canvas签名
示例
<head>
<meta charset="UTF-8">
<title>26_事件</title>
<style>
#test{
position: absolute;
left: 0;
right: 0;
top: 0;
bottom: 0;
margin: auto;
background-color: #BBAAFF;
}
</style>
</head>
<body>
<input type="button" id="clear" value="重签"/>
<input type="button" id="save" value="保存图片"/>
<canvas id="test" width="300" height="300">您的浏览器不支持canvas,请升级</canvas>
<script type="application/javascript">
/*
setCapture()该函数在属于当前线程的指定窗口里设置鼠标捕获。 一旦窗口捕获了鼠标,所有鼠标输入都针对该窗口,无论光标是否在窗口的边界内。
SetCapture,所有鼠标的操作都会在调用该函数的窗口处捕捉到,包括该窗口以外的鼠标操作,你可以看到SetCapture有一个HWND类型的参数(API原型),就是标识这个窗口的,如果不执行这个函数你是捕捉不到窗口以外的操作的,相对应的,ReleaseCapture就是解除这种设定。
常用的是在OnLButtonDown中SetCapture,在OnLButtonUp中ReleaseCapture,这样就可以捕获所有两个消息之间的鼠标移动消息(OnMouseMove),即使鼠标移动到窗口外面。当鼠标在窗口外面点击的时候,被点击的窗口获得焦点,原来的SetCapture也就失效了。
SetCapture和ReleaseCapture必须成对使用。
*/
window.onload=function(){
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.beginPath();
ctx.moveTo(ev.clientX - canvas.offsetLeft,ev.clientY - canvas.offsetTop);
document.onmousemove = function(ev){
ev = ev || window.event;
ctx.save();
ctx.lineTo(ev.clientX - canvas.offsetLeft,ev.clientY - canvas.offsetTop);
ctx.stroke();
ctx.restore();
}
document.onmouseup=function(){
document.onmousemove=document.onmouseup=null;
if(document.releaseCapture){
document.releaseCapture();
}
}
return false;
}
var clearNode = document.querySelector("#clear");
clearNode.onclick = function(){
ctx.clearRect(0,0,canvas.width,canvas.height);
}
var saveNode = document.querySelector("#save");
saveNode.onclick = function(){
var imageBase64 = canvas.toDataURL();
// 生成一个a元素
var a = document.createElement('a');
// 创建一个单击事件
var event = new MouseEvent('click');
// 将a的download属性设置为我们想要下载的图片名称,若name不存在则使用‘下载图片名称’作为默认名称
a.download = name || 'test.png';
// 将生成的URL设置为a.href属性
a.href = imageBase64;
// 触发a的单击事件
a.dispatchEvent(event);
}
}
</script>
</body>
效果