Problem Description:
Project, when implemented using mousemove draw a circle, found the mouse moves too fast, drawing a circle, can not be connected together, an intermediate for the breakpoint, can not form a complete path.
problem analysis:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>事件</title>
<style type="text/css">
*{
margin: 0;
padding: 0;
}
#content{
width: 200px;
height: 200px;
border: 1px solid #ccc;
background-color: blue;
margin: 0 auto;
}
</style>
</head>
<body>
<div id="content"></div>
<script type="text/javascript">
var box=document.getElementById("content");
var isMouseDown=false;
var t=0;
box.addEventListener("mousemove",function(e){
if(isMouseDown){
console.log("move");
/*t++;
console.log(t);*/
}
});
box.addEventListener("mousedown",function(e){
isMouseDown=true;
});
document.addEventListener("mouseup",function(e){
isMouseDown=false;
});
</script>
</body>
</html>
Renderings:
** Reason: ** mouse movement, the movement does not store all the information, but get the mouse position information by taking interpolation method, otherwise, the system will be worn down mouse movement. So there will be, moving too fast, breakpoint problems arise.
solution:
When drawing the trajectories, the most common solution is to think through each move a pixel, you draw a circle, so that all round together, just form a track. (A circle in the figure is a movement of each pixel, drawn round, is connected a track path)
Ideal is good, the reality is cruel. As the above analysis, the response time is not enough granularity mousemove event, the mouse moves too fast, do not move a pixel, in response to a mousemove event, it is not possible to draw a circle by moving a pixel, thereby forming a continuous trajectory path. Shown below, is moved too quickly, the path will be interrupted.
When we change the kinds of ideas, for the first time mousemove response, recorded as a starting point startPoint, the second response is recorded as the end endPoint, the two connected to draw a straight line, an intermediate breakpoint will not appear.
For aesthetics, lineCap properties may be utilized, can ensure straight line rounded at both ends, as follows:
ctx.beginPath();
ctx.lineCap="round";
ctx.moveTo(20,40);
ctx.lineTo(200,40);
ctx.stroke();
So that our problem is solved
demonstration effect: http://zhaoshaobang.github.io/blog/lottery/