您的位置:首页 > 其它

【Canvas】canva实例-星空、日出的效果

2015-01-03 16:52 351 查看
一、描述

模仿星空后黎明到来,日出的场景

二、代码

<!DOCTYPE html>
<html>
<head>
<title></title>
<meta http-equiv="" charset="utf-8">
</head>
<body style="margin:0;padding:0;">
<canvas id="demo"></canvas>
</body>
<script type="text/javascript">
var moonX = 300;
var moonY = 150;
var moonR = 100;
window.onload = function(){
var canvas = document.getElementById('demo');
canvas.width = window.screen.width;
canvas.height = 1600;
var ctx = canvas.getContext('2d');

var linearGradient = ctx.createLinearGradient(0,0,0,1600);
linearGradient.addColorStop(0, "black");
linearGradient.addColorStop(0.65, "#035");
linearGradient.addColorStop(0.8, "orange");
linearGradient.addColorStop(1, "pink");
ctx.fillStyle = linearGradient;
ctx.fillRect(0,0,canvas.width,canvas.height);

ctx.beginPath();
ctx.fillStyle = "yellow";
ctx.arc(moonX,moonY,moonR,Math.PI * 0,Math.PI *2,true);
ctx.closePath();
ctx.fill();

for(var i = 0 ; i < 50 ; i++){
var r = Math.random() * 10 + 5;
var x = Math.random() * canvas.width;
var y = Math.random() * canvas.height * 0.25;
var a = Math.random() * 360;
if((x<(moonX + moonR)) && (x > (moonX - moonR)) &&
(y < (moonY + moonR)) &&(y > (moonY - moonR))){
continue;
}
drawStar(ctx,x,y,r,a);
}

drawSun(ctx);
}

function drawSun(ctx){
var canvas = ctx.canvas;
var sunX = canvas.width * 0.5;
var sunY = canvas.height + moonR;
var interval = setInterval(function(){
ctx.beginPath();
ctx.fillStyle = "red";
ctx.arc(sunX,sunY,moonR,Math.PI * 0,Math.PI *2,true);
ctx.closePath();
ctx.fill();

sunY = sunY - 10;
if(sunY < canvas.height){
clearInterval(interval);
drawText(ctx,"新的一天开始啦!",canvas.width * 0.65,canvas.height * 0.95);
}
},500);
}

function drawText(ctx,text,x,y){
ctx.fillStyle = "yellow";
ctx.font="30px Arial";
ctx.textAlign="start";
ctx.fillText(text,x,y);
}

function drawStar(ctx,x,y,r,rot){
ctx.save();
ctx.translate(x,y);
ctx.rotate(rot/180 *Math.PI);
ctx.scale(r,r);

starPath(ctx);

ctx.fillStyle = "#fb3";
//ctx.strokeStyle = "#fd5";
//ctx.lineWidth = 3 ;
//ctx.lineJoin = "round";

ctx.fill();
// ctx.stroke();

ctx.restore();
}
function starPath(ctx){
ctx.beginPath();
for(var i = 0 ; i < 5 ; i ++){
ctx.lineTo(Math.cos((18 + i*72)/180 * Math.PI),
-Math.sin((18 + i*72)/180 * Math.PI));
ctx.lineTo(Math.cos((54 + i*72)/180 * Math.PI) * 0.5,
-Math.sin((54+ i*72)/180 * Math.PI) * 0.5);
}
ctx.closePath();
}

</script>
</html>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: