现在要实现使用HTML5画布和jQuery实现小球颜色不断变化,依次为红色、绿色、蓝色,如下图
image.png<!DOCTYPE html>
<html>
<head>
<title>HTML5画布和jQuery使小球颜色不断变化</title>
<!-- 引入 Bootstrap -->
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
<!-- jQuery (Bootstrap 的 JavaScript 插件需要引入 jQuery) -->
<script src="https://code.jquery.com/jquery.js"></script>
<!-- 包括所有已编译的插件 -->
<script src="js/bootstrap.min.js"></script>
<meta charset="utf-8">
<style type="text/css">
.list-group-item>a:hover{
cursor:pointer;
}
.nav>li>a:hover{
cursor: pointer;
}
</style>
</head>
<body>
<div style="background-color: black;">
<nav class="navbar-default container navbar-inverse" style="background-color: black;">
<ul class="nav navbar-nav">
<li><a id="quick">快速</a></li>
<li><a id="middle">中速</a></li>
<li><a id="slow">慢速</a></li>
</ul>
</nav>
</div>
<div class="container">
<div class="row">
<div class="col-md-12" style="margin: 20px;background-color: yellow;height: 500px;">
<canvas id="mycanvas"></canvas>
</div>
</div>
</div>
<script type="text/javascript">
var mycanvas,context;
var timer = null;
var index = 1;
function init(){
mycanvas = document.getElementById("mycanvas");
context = mycanvas.getContext("2d");
context.fillStyle = "red";
drawCir();
$("#quick").click(function () {
clearInterval(timer);
timer = setInterval(change,100);
});
$("#middle").click(function () {
clearInterval(timer);
timer = setInterval(change,500);
});
$("#slow").click(function () {
clearInterval(timer);
timer = setInterval(change,1000);
});
}
function clean(){
context.clearRect(0,0,1000,450);
}
//画圆
function drawCir(){
clean();
context.beginPath();
context.arc(100,100,50,0,2*Math.PI);
context.stroke();
context.fill();
}
//改变颜色
function change(){
if (index == 1) {
context.fillStyle = "red";
}else if(index == 2){
context.fillStyle = "green";
}else{
context.fillStyle = "blue";
}
context.fill();
index++;
if (index == 4) {
index = 1;
}
}
//文档就绪
$(document).ready(function(){
init();
timer = setInterval(change,500);
});
</script>
</body>
</html>
网友评论