1. 让canvas的坐标系旋转
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>圆周运动</title>
<style type="text/css">
canvas{
border:1px solid red;
}
</style>
</head>
<body>
<canvas id="mycanvas" width="400" height="400">
您的浏览器不支持canvas
</canvas>
</body>
<script type="text/javascript">
var canvas = document.getElementById("mycanvas");
var context = canvas.getContext("2d");
//移动坐标系,使旋转中心点位于画布中心
context.translate(200,200);
//画小球
function draw(){
context.beginPath();
context.fillStyle = "red";
context.arc(100,100,10,0,Math.PI*2);
context.fill();
}
//让坐标系运动
var everyPercent = Math.PI/100;
function act(){
context.clearRect(0,0,canvas.width,canvas.height);
context.rotate(everyPercent);
draw();
window.requestAnimationFrame(act);
}
act();
</script>
</html>
2. 画一个空心圆,每次只画圆的一小部分,每次清空画布后改变圆的起始角度和终点角度
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>圆周运动2</title>
<style type="text/css">
canvas{
border:1px solid red;
}
</style>
</head>
<body>
<canvas id="mycanvas" width="400" height="400">
您的浏览器不支持canvas
</canvas>
</body>
<script type="text/javascript">
var canvas = document.getElementById("mycanvas");
var context = canvas.getContext("2d");
//移动坐标系使旋转中心点位于画布中心
context.translate(200,200);
//画小球
function draw(start,end){
context.beginPath();
context.strokeStyle = "red";
context.lineWidth = 10;
context.arc(0,0,100,start,end);
context.stroke();
}
var startPer = 0;
var everyPer = Math.PI/30;
function act(){
context.clearRect(-200,-200,canvas.width,canvas.height);
var endPer = startPer + everyPer;
draw(startPer,endPer);
window.requestAnimationFrame(act);
startPer = endPer;
}
act();
</script>
</html>
3. 利用勾股定理,定一个大圆,小球在该圆的轨迹上运行。
原理:大圆半径固定,根据每次改变的角度不同,可以算出小球的X,Y坐标
�原理图.png
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>圆周运动3</title>
<style type="text/css">
canvas{
border:1px solid red;
}
</style>
</head>
<body>
<canvas id="mycanvas" width="400" height="400">
您的浏览器不支持canvas
</canvas>
</body>
<script type="text/javascript">
var canvas = document.getElementById("mycanvas");
var context = canvas.getContext("2d");
//移动坐标系使旋转中心点位于画布中心
context.translate(200,200);
//画小球
function draw(everyPer){
var x = 100 * Math.cos(everyPer);
var y = 100 * Math.sin(everyPer);
context.beginPath();
context.fillStyle = "red";
context.arc(x,y,20,0,Math.PI*2);
context.fill();
}
var everyPer = 0;
function act(){
//清空画布
context.clearRect(-200,-200,canvas.width,canvas.height);
draw(everyPer);
window.requestAnimationFrame(act);
everyPer += Math.PI/60;
}
act();
</script>
</html>
我的博客链接
更多资源就在我的gitHub:https://github.com/huzixian2017
网友评论