知识点
canvas 的宽高设置
js的使用
实例
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <title>鼠标滑动泡泡</title> <meta name="keywords" content="鼠标滑动泡泡"> <meta name="description" content="5月8日,前端复习"> <style type="text/css"> body {margin:0;} #canvas { /* background-color:#fff; */ background-color:#222; display:block; } </style> </head> <body> <canvas id="canvas"></canvas> <script> var canvas = document.querySelector('#canvas');//选中目标元素 var ctx = canvas.getContext('2d');//生成绘制环境并返回 var ww,hh; var balllist = []; function init(){ //浏览器显示页面初始化 canvas.width = ww = window.innerWidth; canvas.height = hh = window.innerHeight; } window.onresize = init; //添加浏览器调整监控事件 init(); function Ball(x,y){ this.x = x; this.y = y; this.r = 50; this.vx = Math.random()*6-3; this.vy = Math.random()*6-3; this.c = '#'+Math.floor(Math.random()*1000000); } Ball.prototype={ draw:function(ctx){ ctx.beginPath(); ctx.arc(this.x,this.y,this.r,0,Math.PI*2,false); //画圆描述画法 X坐标 Y坐标 R半径 圆的起始点 绘制旋转半径,绘制方形 ctx.fillStyle = this.c; // ctx.globalCompositeOperation = 'xor'; //使用异或操作对源图像与目标图像进行组合 ctx.globalCompositeOperation = 'lighter'; //显示源图像 + 目标图像 ctx.fill(); }, update:function(){ this.x+=this.vx; this.y+=this.vy; this.vy*=0.99; this.vx*=0.99; this.r-=0.3; if(this.r < 0){ this.r = 0; } } } canvas.addEventListener('mousemove',function(e){ balllist.push(new Ball(e.clientX,e.clientY))//鼠标移动 绘制球的坐标 }) function render(){ ctx.clearRect(0,0,ww,hh); balllist.forEach(function(ball){ ball.draw(ctx); ball.update(); }) //判断半径小于0的时候,清除/回收 for(var i=0;i<balllist.length;i++){ if(balllist[i].r==0){ balllist.splice(i,1); } } requestAnimationFrame(render); } render(); </script> </body> </html>
运行实例 »
点击 "运行实例" 按钮查看在线实例