Canvas 小球连线

阅读: 评论:0

Canvas 小球连线

Canvas 小球连线

1. 创建canvas画布

1.1 在body标签内创建canvas标签,并添加id元素。

<canvas id="mycanvas"></canvas>

1.2 在script标签中获取dom元素canvas, 并进行设置,第二行为固定写法。

var canvas = document.querySelector("#mycanvas")
var ctx = Context('2d')

1.3 设置画布的宽高分别等于屏幕大小的宽高,宽高分别减10用以呈现完整的画布。

canvas.width = document.documentElement.clientWidth - 10
canvas.height = document.documentElement.clientHeight - 10

1.4 在head头部标签设置画布的样式。 

<style>* {margin: 0;padding: 0;}canvas {display: block;margin: 0 auto;}
</style>

2. 封装小球的构造函数

    function Ball() {this.randomX = il(Math.random() * canvas.width)this.randomY = il(Math.random() * canvas.height)this.r = lor = 'pink'this.dx = il(Math.random() * 10) - 5this.dy = il(Math.random() * 10) - 5this.index = ballArr.lengthif (this.randomX < this.r) {this.x = this.r}else if(this.randomX > canvas.width - this.r) {this.x = canvas.width - this.r}else {this.x = this.randomX}if (this.randomY < this.r) {this.y = this.r}else if(this.randomY > canvas.height - this.r) {this.y = canvas.height - this.r}else {this.y = this.randomY}ballArr.push(this)}

2.1  设置生成小球的随机坐标。

      this.randomX = il(Math.random() * canvas.width)this.randomY = il(Math.random() * canvas.height)

根据画布的宽高来随机生成小球x,y的坐标,il()为向上取整,也可使用Math.floor()同parseInt()向下取整。

2.2 设置小球的半径及颜色。

      this.r = lor = 'pink'

 2.3 设置小球的运动方向。

      this.dx = il(Math.random() * 10) - 5this.dy = il(Math.random() * 10) - 5

生成的数字为1~10之间,需要将生成的数字减5,x轴为负数的球就会往左移动,正数往右;y轴负数往上,正数往下,从而能够达到小球向四面八方运动的一个效果。

2.4 判断小球随机生成的坐标是否让小球在画布之内。

      if (this.randomX < this.r

本文发布于:2024-01-27 20:07:16,感谢您对本站的认可!

本文链接:https://www.4u4v.net/it/17063572332363.html

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。

上一篇:POJ
标签:小球   Canvas
留言与评论(共有 0 条评论)
   
验证码:

Copyright ©2019-2022 Comsenz Inc.Powered by ©

网站地图1 网站地图2 网站地图3 网站地图4 网站地图5 网站地图6 网站地图7 网站地图8 网站地图9 网站地图10 网站地图11 网站地图12 网站地图13 网站地图14 网站地图15 网站地图16 网站地图17 网站地图18 网站地图19 网站地图20 网站地图21 网站地图22/a> 网站地图23