Canvas之太阳与地球

来源:互联网 发布:南大碎尸案推理 知乎 编辑:程序博客网 时间:2024/06/11 01:10
<!DOCTYPE html><html lang="en" xmlns="http://www.w3.org/1999/xhtml"><head>    <meta charset="utf-8" />    <title>太阳与地球</title></head><body>    <canvas id="canvas" width="1000" height="1000" style="background: #000">浏览器不支持Canvas元素</canvas>    <script>        var canvas = document.getElementById('canvas');        var context = canvas.getContext('2d');        var time = 0;        function draw() {            //清除之前的内容,重新画            context.clearRect(0, 0, 1000, 1000);            //画轨道            context.strokeStyle = "white";            context.beginPath();            context.arc(500, 500, 100, 0, 360, false);            context.closePath();            context.stroke();            //画太阳            context.beginPath();            context.arc(500, 500, 20, 0, 360, false);            context.closePath();            //参数(内圆心x,内圆心y,内半径,外圆心x,外圆心y,外半径)            var sunColor = context.createRadialGradient(500, 500, 0, 500, 500, 20);            /*              渐变              第一个参数:一个浮点数,从最中间0开始,到1结束              第二个参数:颜色参数            */            sunColor.addColorStop(0, "#f80");            sunColor.addColorStop(0.5, "#f90");            sunColor.addColorStop(1, "#fa0");            context.fillStyle = sunColor;            context.fill(); //太阳需要填充            // context.stroke();            //画地球,地球要动,需要在异次元空间里画            context.save();            context.translate(500, 500);//设置异次元的(0,0)点            context.rotate((time * 360 / 365) * Math.PI / 180);            context.beginPath();            context.arc(0, -100, 10, 0, 360, false);            context.closePath();            var earthColor = context.createRadialGradient(0, -100, 0, 0, -100, 10);//这里内外圆心要相等            earthColor.addColorStop(0, "#78b1e8");//78ble8            earthColor.addColorStop(1, "#050c12");//050c12            context.fillStyle = earthColor;            context.fill();            //  context.stroke();            context.restore();            time += 1;        }        setInterval(draw, 50);//每隔50毫秒刷新一次页面,让地球动起来注意这里draw不要加上双括号    </script></body></html>

0 0
原创粉丝点击