HTML5 Canvas创建二次运动动画

gooood个人博客网站

canvas

要使用HTML5 Canvas创建二次运动动画,我们可以为每个帧增加vx(水平速度),vy(垂直速度)或对象的vx和vy,然后更新对象的位置, 根据加速度方程:
距离=速度*时间+ 1/2 *加速度*时间^ 2
html代码:
<!DOCTYPE HTML> <html> <head> <style> body { margin: 0px; padding: 0px; } </style> </head> <body> <canvas></canvas> <script> window.requestAnimFrame = (function(callback) { return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame || function(callback) { window.setTimeout(callback, 1000 / 60); }; })(); function drawRectangle(myRectangle, context) { context.beginPath(); context.rect(myRectangle.x, myRectangle.y, myRectangle.width, myRectangle.height); context.fillStyle = '#8ED6FF'; context.fill(); context.lineWidth = myRectangle.borderWidth; context.strokeStyle = 'black'; context.stroke(); } function animate(myRectangle, canvas, context, startTime) { // update var time = (new Date()).getTime() - startTime; // pixels / second^2 var gravity = 200; myRectangle.y = 0.5 * gravity * Math.pow(time / 1000, 2); if(myRectangle.y > canvas.height - myRectangle.height - myRectangle.borderWidth / 2) { myRectangle.y = canvas.height - myRectangle.height - myRectangle.borderWidth / 2; } lastTime = time; // clear context.clearRect(0, 0, canvas.width, canvas.height); // draw drawRectangle(myRectangle, context); // request new frame requestAnimFrame(function() { animate(myRectangle, canvas, context, startTime); }); } var canvas = document.getElementById('myCanvas'); var context = canvas.getContext('2d'); var myRectangle = { x: 239, y: 0, width: 100, height: 50, borderWidth: 5 }; drawRectangle(myRectangle, context); // wait one second before dropping rectangle setTimeout(function() { var startTime = (new Date()).getTime(); animate(myRectangle, canvas, context, startTime); }, 2000); </script> </body> </html>

本文内容由用户注册发布,仅代表作者或来源网站个人观点,不代表本网站的观点和立场,与本网站无关。本网系信息发布平台,仅提供信息存储空间服务,其原创性以及文中陈述文字和内容未经本站证实,对本文以及其中全部或者部分内容、文字的真实性、完整性、及时性本网站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。如因作品内容侵权需删除与其他问题需要同本网联系的,请尽快通过本网的邮箱或电话联系。 
THE END
分享
二维码
< <上一篇
下一篇>>