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

canvas小球落地弹动效果

2018-2-11 14:42| 发布者: antzone| 查看: 736| 评论: 0|来自: 蚂蚁部落

分享一段代码实例,他事先了抛落小球,然后小球会因为重力原因出现弹动效果。

代码是由canvas实现,感兴趣的朋友可以做一下参考。

代码实例如下:

[HTML] 纯文本查看 复制代码运行代码
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="author" content="http://www.softwhy.com/" />
<title>蚂蚁部落</title>
</head>
<body>
<canvas id="canvas"></canvas>
<script type="text/javascript">
var ball = {
  x: 512,
  y: 100,
  r: 20,
  g: 2,
  vx: -4,
  vy: -5,
  color: "#005588"
}; // g:速度
window.onload = function() {
  var canvas = document.getElementById("canvas");
 
  width = canvas.width = 1024;
  height = canvas.height = 768;
 
  var context = canvas.getContext("2d");
  time = 50;
  setInterval(function() {
    render(context);
    update();
  }, time)
}
 
function update() {
  ball.x += ball.vx;
  ball.y += ball.vy;
  ball.vy += ball.g;
  if (ball.y >= 768 - ball.r) {
    ball.y = 768 - ball.r;
    ball.vy = -ball.vy * 0.5;
  }
}
 
function render(cxt) {
  cxt.clearRect(0, 0, cxt.canvas.width, cxt.canvas.height);
  cxt.beginPath();
  cxt.arc(ball.x, ball.y, ball.r, 0, 2 * Math.PI);
  cxt.closePath();
  cxt.fill();
}
</script>
</body>
</html>

鲜花

握手

雷人

路过

鸡蛋

最新评论

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

GMT+8, 2018-2-19 15:55 , Processed in 0.093899 second(s), 21 queries .

Powered by Discuz! X3.2 Licensed

Copyright © 2012-2017 Design: 蚂蚁部落

返回顶部