原文链接:https://www.jb51.net/article/75436.htm
本文实例讲述了javascript实现很浪漫的气泡冒出特效代码。分享给大家供大家参考。具体如下:
运行效果截图如下:
![](https://i-blog.csdnimg.cn/blog_migrate/9f1d6911d64aac28ce75115130a405af.jpeg)
具体代码如下:
实现思路:HTML里只需要一个CANVAS元素,Javascript里操作canvas
1、给canvas里绘制背景图片
2、在绘制半径为0-10px的圆形,x坐标屏幕水平随机,y所标竖直大于屏幕高度。
圆形背景色可以是随机,那就是各种色彩了!
利用计时器控制y--
构建html
?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | <!doctype html> < html lang = "en" > < head > < meta charset = "UTF-8" > < meta name = "Generator" content = "EditPlus®" > < meta name = "Author" content = "" > < meta name = "Keywords" content = "" > < meta name = "Description" content = "" > < title >5多个小球往上运动</ title > < style > </ style > </ head > < body > < div id = "d1" > < canvas id = "canvas" ></ canvas > </ div > </ body > </ html > |
js代码
?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 | <script> var canvas=document.getElementById( "canvas" ); var context=canvas.getContext( "2d" ); canvas.width=window.innerWidth; canvas.height=window.innerHeight; function Circle(){ this .x=Math.random()*canvas.width; this .y=canvas.height; this .r=Math.random()*10; //绘制圆形 this .paint= function (){ context.beginPath(); context.arc( this .x, this .y, this .r,0,Math.PI*2); context.fillStyle= "white" ; context.globalAlpha = 0.5; context.fill(); } //控制圆形移动 this .step= function (){ this .y--; } } var circles=[]; function createCircles(){ var circle= new Circle(); //?????? circles[circles.length]=circle; } function paintCircles(){ for ( var i=0;i<circles.length;i++){ circles[i].paint(); } } function stepCircles(){ for ( var i=0;i<circles.length;i++){ circles[i].step(); } } var myimg= new Image(); myimg.src= "images/demo-1.png" ; var timer= "" ; setInterval( function (){ context.drawImage(myimg,0,0); timer++; if (timer%20==0){ createCircles(); } paintCircles(); stepCircles(); },10); </script> |
需要在自己的网站中添加浪漫元素,这不失为一种好的方式,希望大家灵活运用javascript实现气泡冒出特效,谢谢大家的阅读。