有段时间没碰 canvas 了, 今天回顾了一下很久之前做的效果
html 代码
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <meta http-equiv="X-UA-Compatible" content="ie=edge">
- <title>
canvas 小球
- </title>
- <style>
- *{ margin: 0; padding: 0; } #canvas{ background-color: black; }
- </style>
- </head>
- <body>
- <canvas id="canvas">
- </canvas>
- <script type="text/javascript">
- const canvas = document.getElementById("canvas");
- const ctx = canvas.getContext('2d');
- canvas.width = document.documentElement.clientWidth;
- canvas.height = document.documentElement.clientHeight;
- // 小球
- class Ball {
- // 小球的三个属性 x,y,color
- constructor(x, y, color) {
- this.x = x;
- this.y = y;
- this.color = color;
- this.r = 20;
- }
- // 不需要用, 进行分隔
- // 绘制小球
- getBall() {
- ctx.save();
- ctx.beginPath();
- ctx.arc(this.x, this.y, this.r, 0, Math.PI * 2);
- ctx.fillStyle = this.color;
- ctx.fill();
- ctx.restore();
- }
- }
- // 移动小球
- // 继承 Ball 的属性
- class movingBall extends Ball {
- constructor(x, y, color) {
- // 注意: 在派生的类中, 在你可以使用'this'之前, 必须先调用 super()
- // 详细查看 https://developer.mozilla.org/zh-CN/docs/web/JavaScript/Reference/Operators/super
- super(x, y, color);
- // 移动时小球的变化量
- this.dx = Math.random() * 20 - 10;
- this.dy = Math.random() * 20 - 10;
- this.dr = Math.random() * 2 + 1;
- }
- loadBall() {
- this.x += this.dx;
- this.y += this.dy;
- this.r -= this.dr;
- if (this.r < 0) {
- this.r = 0;
- }
- }
- }
- // 实例化小球
- let ballArr = [];
- let colorArr = ['red', 'yellowgreen', 'pink', 'blue', 'white', 'green', 'orange'];
- // 如果随机色写在这会导致生成一种随即色, 鼠标移动时只会显示当前一种随即色, 放在监听里面会由于每次 mousemove 时就会生成一种随机色
- // let randomColor = colorArr[Math.floor( Math.random()*(colorArr.length-1))];
- // 监听鼠标移动
- canvas.addEventListener("mousemove",
- function(e) {
- let ball = new movingBall(e.offsetX, e.offsetY, colorArr[Math.floor(Math.random() * colorArr.length)]);
- ballArr.push(ball);
- });
- setInterval(function() {
- ctx.clearRect(0, 0, canvas.width, canvas.height);
- for (let i = 0; i < ballArr.length; i++) {
- ballArr[i].getBall();
- ballArr[i].loadBall();
- }
- },
- 50)
- </script>
- </body>
- </html>
来源: http://www.qdfuns.com/article/46720/0910ac6134e2ce07b0cd5a5d79120009.html