1. 程式人生 > >h5 canvas繪製的旋轉小球

h5 canvas繪製的旋轉小球

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>$</title>
</head>
<body>
<canvas id="canvas" width="800" height="600" style="border:1px solid red"></canvas>
</body>
<script>
function RotateBall(opt) {
for (
var key in opt) { this[key] = opt[key]; } this.init() } RotateBall.prototype = { init: function () { this.loop(); }, loop:function(){ var self = this; this.timer = setInterval(function () { self.ctx.clearRect(0,0,self.ctx.canvas.width,self.ctx.canvas.height); self.ctx.font = '20px 微軟雅黑
'; self.ctx.textAlign = 'center'; self.ctx.textBaseline = 'middle'; self.start += 0.01 * Math.PI; //繪製 self.drawBigCircle(); self.drawSmallCircles(); }, 20); }, drawBigCircle: function () { var ctx = this.ctx; ctx.beginPath(); ctx.arc(this.bigX, this.bigY, this.bigRadius, 0, 2 * Math.PI
); ctx.stroke(); }, drawSmallCircles: function () { var dataL = this.data.length; var radian = 2 * Math.PI / dataL; var bigRadius = this.bigRadius; var bigX = this.bigX; var bigY = this.bigY; var datas = this.data; for (var i = 0; i < dataL; i++) { var startRadian = radian * i + this.start; var b = bigRadius * Math.cos(startRadian); var h = bigRadius * Math.sin(startRadian); var smallX = bigX + b; var smallY = bigY + h; this.drawSmallCircle(smallX, smallY); this.drawSmallCircle(startRadian); this.drawText(datas[i], smallX, smallY); } }, drawSmallCircle: function (smallX, smallY) { var ctx = this.ctx; ctx.save() ctx.beginPath(); ctx.arc(smallX, smallY, this.smallRadius, 0, 2 * Math.PI); ctx.fillStyle = 'skyblue'; ctx.fill(); ctx.restore(); }, drawText: function (data, smallX, smallY) { ctx.save() ctx.beginPath(); ctx.fillStyle = 'orange'; ctx.fillText(data, smallX, smallY); ctx.restore(); } }; var canvas = document.getElementById("canvas"); var ctx = canvas.getContext("2d"); var data = ['php', '前端', 'ios', '安卓', 'python', 'java']; var obj = { ctx: ctx, bigX: 300, bigY: 300, bigRadius: 150, data: data, smallRadius: 30, start: 0 } var rball = new RotateBall(obj); </script> </html>