今天用js制作了一幅海上生明月的图。
首先,从网上找一张大海的图片作为背景,如下图:
其次,我们再找一张含有月亮的图片,用抠图软件将月亮扣下来,如图:
方法实现代码如下:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset="utf-8">
<title>海上生明月呀</title>
<script type="text/javascript" src="moon.js"defer>
</script>
<style>
#color{
width:100%;
height:1000px;
}
div{
position:absolute;
}
img{
position:absolute;
filter:alpha(opacity=500);/* IE */
-moz-opacity:1;/* Moz + FF */
opacity: 1;/* 支持CSS3的浏览器(FF 1.5也支持)*/
}
</style>
</head>
<body>
<div id="color" ></div>
<div id="divimg"><img src="moon.png" width="150" height="150"></div>
<div id="poem"style="margin-top:300px;margin-left:700px;font-size:40px;font-weight:bold;"> </div>
</body>
</html>
js文件如下:
var tg=document.getElementById("color");
tg.style.backgroundImage='url(大海.png)';
tg.style.backgroundRepeat='no-repeat';
tg.style.backgroundSize='100%';
var img=document.getElementById("divimg");
var x=0,y=500;
var xSpeed=2,ySpeed=1;
//设置图片的最大浮动的高度和宽度
//var w=document.documentElement.clientWidth-110,h=document.documentElement.clientHeight-160;
function floatimg(){
var H=0;
//月亮如果到达指定位置,则停住,否则继续移动。
if(x==850||y==50){xSpeed=xSpeed;y=ySpeed;H=1}
else{ x+=xSpeed;
y-=ySpeed;
img.style.top=y+"px";
img.style.left=x+"px";
}
if(H==1)
{
var tt=document.getElementById("poem");
tt.innerHTML ="海上生明月, 饭大王最帅。";
}
//延迟调用函数floatimg(),每个40毫秒调用一次
setTimeout("floatimg()",40);
}
floatimg();
实现结果为:
这幅图主要运用到了setTimeout(),通过该方法,延时调用floating函数,从而达到月亮移动的效果。当然,如果想要月亮有不同的移动效果,如移动到边框的时候再反弹,或者从一个点向不同的方向移动,都可以通过修改图片初始坐标或者移动速度,以及floating函数中if的限制条件来达到目的。
此外,我在function floating()的for循环里加入了一个文本,借助H来判断月亮是否移动到指定位置,当移动到指定位置时再在网页中显示文本,从而达到文本延时显示的效果。
以上就是“海上生明月”图的制作方法,主要运用了js和setTimeout函数。如果大家有什么别的更好的实现方法,欢迎留言评论,大家一起学习呀。