canvas实现点连线动画

给定一系列坐标(x, y)点, 实现将各个点按照先后顺序连接起来的动画。还有两个要求:

1.点与点之间直接用线段连接, 不用考虑曲线

2.动画支持暂停, 继续, 重头开始播放功能

这个功能该怎么实现呢,我们首先会想到HTML5点新功能canvas。废话少说直接上实现代码

 <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>题2</title>
<style type="text/css">
textarea{
height: 100px;
}
.btns{
margin: 10px;
}
button{
width: 80px;
}
</style>
</head>
<body>
<canvas id="canvas" width="500" height="500"></canvas>
<div>
<label>坐标</label><textarea id="dots" type='text'></textarea>
<button id='change'>修改</button>
</div>
<br/>
<div class="btns">
<button id='start'>开始</button>
<button id='stop'>暂停</button>
<button id='continue'>继续</button>
</div>
<script>
//获取指定的canvas元素
var canvas = document.getElementById('canvas');
//调用canvas元素的getContext 方法访问获取2d渲染的上下文
var context = canvas.getContext('2d');
var dotarr = [{"x":280,"y":200},{"x":180,"y":150},{"x":100,"y":250},{"x":280,"y":300},{"x":180,"y":400},
{"x":80,"y":350}];
var isStop = false;
document.getElementById('dots').value=JSON.stringify(dotarr);
function drawline(dots){
for(var i in dots){
//context.clearRect(0, 0, canvas.width, canvas.height)
//window.requestAnimationFrame(drawline,canvas);
var dot=dots[i];
var todot=dots[i];
var time='';
localStorage.setItem('length',dots.length);
if((parseInt(i)+1)<dots.length){
todot=dots[parseInt(i)+1];
}
(function(dot,todot,time,i){
time=setTimeout(function(){
//context.clearRect(0, 0, canvas.width, canvas.height)
context.beginPath();
context.moveTo(dot.x,dot.y);
context.lineTo(todot.x,todot.y);
localStorage.setItem('index',i);
localStorage.setItem("t", time);
context.closePath();
context.stroke();
},(parseInt(i)+1)*1000);
})(dot,todot,time,i)
}
}
document.getElementById("change").onclick=function(){
dotarr=JSON.parse(document.getElementById('dots').value);
}
document.getElementById("start").onclick=function(){
context.clearRect(0, 0, canvas.width, canvas.height);
var t=parseInt(localStorage.getItem("t"));
var length=parseInt(localStorage.getItem('length'));
isStop=true;
for(var i=t;i<=(t+length);i++){
clearTimeout(i);
}
drawline(dotarr);
}
document.getElementById("stop").onclick=function(){
var t=parseInt(localStorage.getItem("t"));
var length=parseInt(localStorage.getItem('length'));
isStop=true;
for(var i=t;i<=(t+length);i++){
clearTimeout(i);
}
console.log('暂停'); }
document.getElementById("continue").onclick=function(){
if(isStop){
var index=parseInt(localStorage.getItem('index'));
var newdots=dotarr.slice(index+1);
console.log(newdots);
drawline(newdots);
isStop=false;
console.log('继续');
}
}
</script>
</body>
</html>

效果如下

canvas实现点连线动画

每次点开始都会重绘整个动画,点击暂停和继续会在控制台打印日志,非暂停状态下点击继续无效。

@原创版权所有,要转载请注明出处,否则追究版权责任

上一篇:Xcode 创建 支持IOS4.3以上版本的应用的方法


下一篇:javascript的insertBefore、insertAfter和appendChild简单介绍