栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

使用canvas画一个小球自由落体的效果

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

使用canvas画一个小球自由落体的效果

<!DOCTYPE html><html><head>  <title>小球自由落体</title>  <style>    * {      margin: 0;      padding: 0;      font-size: 0;    }    html,    body {      position: relative;      height: 100%;      width: 100%;    }  </style></head><body></body><script>  //获取屏幕参数  var Height = window.innerHeight;  var Width = window.innerWidth;  // 创建canvas  var canvas = document.createElement("canvas");  canvas.setAttribute("id", "ball");  document.body.appendChild(canvas);  canvas.setAttribute("height", Height);  canvas.setAttribute("width", Width);  var Ball;//创建实例  const STRATSPEED = 0;//初始速度  const ACCELERATION = 10;//加速度  const ANIMATESPEED = 0.5;//动画速度,数值越大运动越快,速度越小运动越慢  function initBall() {    //小球实例    Ball = {      color: "red",      radius: 20    }    Ball.y = Ball.radius;    Ball.x = Height / 2 + Ball.radius;    Ball.speed = STRATSPEED;    ctx.fillStyle = Ball.color;  }  function draw() {    ctx.beginPath();    ctx.arc(Width / 2, Ball.y, Ball.radius, 0, 2 * Math.PI);    ctx.fill();  }  function render() {    // 小球落地前自由下落    if (Ball.y < Height - 2 * Ball.radius) {      ctx.clearRect(0, 0, Width, Height);      Ball.y += Ball.speed * ANIMATESPEED + 0.5 * ACCELERATION * Math.pow(ANIMATESPEED, 2);      Ball.speed += ACCELERATION * ANIMATESPEED;      draw();          }  }  function animate() {    render();    window.requestAnimationframe(animate);  }  if (canvas.getContext) {    var ctx = canvas.getContext("2d");    initBall();    draw();    animate();  }</script><script>  window.onresize = function () {    Height = window.innerHeight;    Width = window.innerWidth;    canvas.setAttribute("height", Height);    canvas.setAttribute("width", Width);    initBall();    draw();  }</script></html>
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/393721.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号