html5鼠标画任意线条

2015年11月24日 前端技术 暂无评论 阅读 47 views 次

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Canvas</title>
<meta name = "viewport" content = "width = device-width, user-scalable = no">
</head>
<body>
<canvas id="canvas" ></canvas>
<script type="text/javascript" charset="utf-8">
//get canvas
var canvas = document.getElementById("canvas");
//full screen
canvas.width=window.innerWidth;
canvas.height=window.innerHeight;
//是否支持触摸
//var touchable = 'createTouch' in document;

var touchable=1;

if (touchable) {
canvas.addEventListener('mousedown', onTouchStart, false);
// canvas.addEventListener('mouseover', onTouchMove, false);
canvas.addEventListener('mouseup', onTouchMove, false);
}
else
{
alert("touchable is false !");
}
//上一次触摸坐标
var lastX;
var lastY;

var ctx =canvas.getContext("2d");
ctx.lineWidth=10;//画笔粗细
ctx.strokeStyle="#FF0000";//画笔颜色

//触摸开始事件
function onTouchStart(event) {
event.preventDefault();
lastX=event.clientX;
lastY=event.clientY;
drawRound(lastX,lastY);

}
//触摸滑动事件
function onTouchMove(event) {
try
{
event.preventDefault();
drawLine(lastX,lastY,event.clientX,event.clientY);
lastX=event.clientX;
lastY=event.clientY;
}
catch(err){
alert( err.description);
}

}

//画圆
function drawRound(x,y)
{
ctx.fillStyle="#FF0000";
ctx.beginPath();
ctx.arc(x,y,5,0,Math.PI*2,true);
ctx.closePath();
ctx.fill();
}
//画线
function drawLine(startX,startY,endX,endY)
{
ctx.beginPath();
ctx.lineCap="round";
ctx.moveTo(startX,startY);
ctx.lineTo(endX,endY);
ctx.stroke();
}

</script>
</body>
</html>

 

查看demo: Noname1

效果:2015-11-24_235434

给我留言

您必须 登录 才能发表留言!

Copyright © 大一网 保留所有权利.  

用户登录

分享到: