[js高手之路]html5 canvas动画教程 - 重力、摩擦力、

      2020-03-18 00:13      HTML5

上节,我们讲了匀速运动,本节分享的运动就更有意思了:

加速运动:

1 <head> 2<meta charset='utf-8' /> 3<style> 4 #canvas { 5 border: 1px dashed #aaa; 6 } 7</style> 8<script src="./ball.js"></script> 9<script>10window.onload = function () {11var oCanvas = document.querySelector("#canvas"),12oGc = oCanvas.getContext('2d'),13width = oCanvas.width, height = oCanvas.height,14ball = new Ball( 0, height / 2 ),15vx = 0,16ax = 0.1;17(function linear() {18oGc.clearRect(0, 0, width, height);19 ball.fill( oGc );20ball.x += vx;21vx += ax;22 requestAnimationFrame(linear);23 })();24 }25</script>26 </head>27 <body>28<canvas></canvas>29 </body>

加速度分解与合成

1 <head> 2<meta charset='utf-8' /> 3<style> 4 #canvas { 5 border: 1px dashed #aaa; 6 } 7</style> 8<script src="./ball.js"></script> 9<script>10window.onload = function () {11var oCanvas = document.querySelector("#canvas"),12oGc = oCanvas.getContext('2d'),13width = oCanvas.width, height = oCanvas.height,14ball = new Ball( 0, 0 ),15a = 0.3,16ax = a * Math.cos( 25 * Math.PI / 180 ),17ay = a * Math.sin( 25 * Math.PI / 180 ),18vx = 0,19vy = 0;20(function linear() {21oGc.clearRect(0, 0, width, height);22 ball.fill( oGc );23ball.x += vx;24ball.y += vy;25vx += ax;26vy += ay;27 requestAnimationFrame(linear);28 })();29 }30</script>31 </head>32 <body>33<canvas></canvas>34 </body>

抛物线运动:

1 <head> 2<meta charset='utf-8' /> 3<style> 4 #canvas { 5 border: 1px dashed #aaa; 6 } 7</style> 8<script src="./ball.js"></script> 9<script>10window.onload = function () {11var oCanvas = document.querySelector("#canvas"),12oGc = oCanvas.getContext('2d'),13width = oCanvas.width, height = oCanvas.height,14ball = new Ball( 0, height / 2 ),15vy = -10,16vx = 5,17gravity = 0.2;18(function linear() {19oGc.clearRect(0, 0, width, height);20 ball.fill( oGc );21ball.y += vy;22ball.x += vx;23vy += gravity;24 requestAnimationFrame(linear);25 })();26 }27</script>28 </head>29 <body>30<canvas></canvas>31 </body>

重力弹跳:

1 <head> 2<meta charset='utf-8' /> 3<style> 4 #canvas { 5 border: 1px dashed #aaa; 6 } 7</style> 8<script src="./ball.js"></script> 9<script>10window.onload = function () {11var oCanvas = document.querySelector("#canvas"),12oGc = oCanvas.getContext('2d'),13width = oCanvas.width, height = oCanvas.height,14ball = new Ball( width / 2, 20 ),15vy = 0,16gravity = 0.2,17bounce = -0.6;18(function linear() {19oGc.clearRect(0, 0, width, height);20 ball.fill( oGc );21ball.y += vy;22if ( ball.y > canvas.height - ball.radius ) {23ball.y = canvas.height - ball.radius;24vy *= bounce;25 }26vy += gravity;27 requestAnimationFrame(linear);28 })();29 }30</script>31 </head>32 <body>33<canvas></canvas>34 </body>

抛物线与重力弹跳运动


上一篇:Canvas 3D 地球旋转

下一篇:没有了