<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title></title></head><body> <div id="box" style="width: 500px;height: 500px;margin: 0 auto;"> <canvas onclick="clcan(event)" id="can" width="500px" height="100px" style="border: 1px solid black;"> </canvas> <canvas id="myCanvas" width="500px" height="100px" style="border: 1px solid black;"> </canvas> </div> <script> function GetRandomNum(Min, Max) { var Range = Max - Min; var Rand = Math.random(); return (Min + Math.round(Rand * Range)); } function mouseCoords(ev) { var e = event || window.event; var x = e.offsetX || e.layerX; var y = e.offsetY || e.layerY; return { x, y }; } var globl_w = 500; var globl_h = 500; makerect(0, 0, globl_w, globl_w); //鼠标点击生成圆 function clcan(e) { var ev = ev || window.event; var mousePos = mouseCoords(ev); mousePosX = mousePos.x; mousePosY = mousePos.y; console.log(mousePosX); console.log(mousePosY); makearc(mousePosX, mousePosY, GetRandomNum(4, 4), 0, 180, 'red'); } function myAnimation() { ctx.clearRect(0, 0, globl_w, globl_h); } //生成圆 function makearc(x, y, r, s, e, color) { var can = document.getElementById('can'); var ctx = can.getContext("2d"); ctx.clearRect(0, 0, 500, 500); ctx.beginPath(); ctx.fillStyle = color; ctx.arc(x, y, r, s, e); ctx.fill(); } function makerect(x, y, w, h) { var can = document.getElementById('can'); var ctx = can.getContext("2d"); ctx.strokeRect(x, y, w, h); } </script> <script> const canvas = document.getElementById('myCanvas') const ctx = canvas.getContext('2d'); let ballArr = [] // 获取随机色彩 function getRandomColor() { let arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 'a', 'b', 'c', 'd', 'e', 'f']; let colorArr = [] for (let i = 0; i < 3; i++) { colorArr.push(arr[parseInt(Math.random() * 16)]) } return `#${colorArr.join('')}` } // 鼠标挪动时成果 canvas.addEventListener('mouseover', () => { canvas.addEventListener('mousemove', (e) => { new Ball(e.offsetX, e.offsetY, 15, getRandomColor()); }) }) // 鼠标点击时成果 canvas.addEventListener('click', (e) => { for (let i = 0; i < 20; i++) { new Ball(e.offsetX, e.offsetY, i, getRandomColor()); } }) setInterval(() => { ctx.clearRect(0, 0, document.body.clientWidth, document.body.clientHeight) ballArr.forEach(item => { item.render(); item.update() }) }, 10) class Ball { constructor(x, y, r, color) { this.x = x; this.y = y; this.r = r; this.dx = Math.random() * 10 - 5 this.dy = Math.random() * 10 - 5 this.color = color; ballArr.push(this) } remove() { let index = ballArr.findIndex(item => item === this) ballArr.splice(index, 1) } render() { ctx.beginPath(); ctx.fillStyle = this.color; ctx.arc(this.x, this.y, this.r, 0, 2 * Math.PI); ctx.fill(); } update() { this.r -= .1; this.x -= this.dx; this.y -= this.dy; if (this.r <= 0) { this.remove() return; } this.render() } } </script></body></html>