1. var canvas = document.getElementsByTagName('canvas')[0];
    2. const ctx = canvas.getContext('2d');
    3. var arrBall = [];
    4. const Ball = class {
    5. constructor({ x, y, r }) {
    6. this.x = x;
    7. this.y = y;
    8. this.r = r;
    9. this.color = this.randomColor();
    10. this.dx = parseInt(Math.random() * 10) - 5; //随机数-5~5
    11. this.dy = parseInt(Math.random() * 10) - 5; //随机数-5~5
    12. arrBall.push(this);
    13. }
    14. update() {
    15. this.x += this.dx;
    16. this.y += this.dy;
    17. this.r -= 3;
    18. if (this.r <= 0) {
    19. this.r = 0;
    20. arrBall.shift();
    21. }
    22. }
    23. render() {
    24. ctx.beginPath();
    25. ctx.arc(this.x, this.y, this.r, 0, Math.PI * 2);
    26. ctx.fillStyle = this.color;
    27. ctx.fill();
    28. }
    29. randomColor() {
    30. const type = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 'a', 'b', 'c', 'd', 'e', 'f'];
    31. let color = '#';
    32. for (let i = 0; i < 6; i++) {
    33. let random = parseInt(Math.random() * 16);
    34. color += type[random];
    35. }
    36. return color;
    37. }
    38. }
    39. ; (function () {
    40. function init() {
    41. bindEvent();
    42. }
    43. function bindEvent() {
    44. canvas.addEventListener('mousemove', function (e) {
    45. new Ball({
    46. x: e.offsetX,
    47. y: e.offsetY,
    48. r: 20
    49. });
    50. console.log(arrBall)
    51. }, false)
    52. }
    53. setInterval(function () {
    54. ctx.clearRect(0, 0, canvas.width, canvas.height);
    55. for (i = 0; i < arrBall.length; i++) {
    56. arrBall[i].update();
    57. if(arrBall[i]){
    58. arrBall[i].render();
    59. }
    60. }
    61. }, 20);
    62. init();
    63. })();