快捷导航
蚂蚁部落 网站首页 实例代码 canvas实例 查看内容

canvas小球抛物线运动

2018-3-15 17:41| 发布者: admin| 查看: 218| 评论: 0|来自: 蚂蚁部落

分享一段代码实例,它利用canvas实现了小球的抛射效果。

简单的抛物线效果,代码实例如下:

[HTML] 纯文本查看 复制代码运行代码
<!DOCTYPE html>
<html>
<head>
<meta charset=" utf-8">
<meta name="author" content="http://www.softwhy.com/" />
<title>蚂蚁部落</title>
<style>
html,body,canvas{
  width:100vw;
  height:100vh;
  background:#000000;
  overflow:hidden;
}
</style>
<script>
setTimeout(() => {
  let canvas = document.querySelector('canvas');
  let context = canvas.getContext('2d');
  canvas.width = canvas.offsetWidth;
  canvas.height = canvas.offsetHeight;

  let pointer = {
      x: 0,
      y: canvas.height / 2
  };

  let render =  () => {
    context.clearRect(0, 0, canvas.width, canvas.height);
    context.fillStyle = "green";
    context.beginPath();
    context.arc(pointer.x ,pointer.y, 100, 0, 2 * Math.PI, false);
    context.fill();
  };

  let vx = 7;
  let vy = -7;
  let run;
  ( run= () => {
    pointer.x += vx; // 位置恒定变化
    vy += 0.1; // 速度恒定变化
    pointer.y += vy;

    if (pointer.x > canvas.width 
       || pointer.y > canvas.height) {
      pointer.x = 0;
      pointer.y = canvas.height / 2;
      vy = -7;
    }
    render();
    requestAnimationFrame(run)
  })();
}, 500);
</script>
</head>
<body>
<canvas></canvas>
</body>
</html>



鲜花

握手

雷人

路过

鸡蛋

最新评论

关于我们|手机版|小黑屋| ( 鲁ICP备10022556号-3 )

GMT+8, 2018-4-21 10:11 , Processed in 0.098120 second(s), 22 queries .

Powered by Discuz! X3.2 Licensed

Copyright © 2012-2017 Design: 蚂蚁部落

返回顶部