亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定

用canvas和JS制作的一個小球做圓周運動

標簽:
Html5 JavaScript

学习了下canvas,用canvas做了一个小例子
输入代码

<canvas id="canvas" width="600" height="600"></canvas>
window.onload=function(){
        var canvas=document.querySelector("#canvas"),
            ctx=canvas.getContext("2d"),//获取绘画环境
            ball=new Ball(),//实例化构造方法
            speed=0.1,
            range=100,
            angle=0;
            ball.x=0;
            ball.y=0,
            widths=canvas.width/2,
            heights=canvas.height/2;
            (function drawFrame(){
                //requestAnimationFrame可以监听到每一个像素的运动效果,浏览器定义的运动的事件
                window.requestAnimationFrame(drawFrame,canvas);
                //ctx.clearRect(0,0,canvas.width,canvas.height);
                ball.y=heights+range*Math.sin(angle);
                ball.x=widths+range*Math.cos(angle);
                angle+=speed;
                ball.draw(ctx);
            })();   
    }
        function Ball(radius,color){
            radius=radius  40;
            color=color  randomColor();//color  '#f00';
            this.radius=radius;
            this.color=color;
            this.lineWidth=1;
            this.scaleX=1;
            this.scaleY=1;
            this.rotation=0;
        }
        Ball.prototype.draw=function(ctx){
            //保存
            ctx.save();
            //效果
            ctx.translate(this.x,this.y);//映射位置
            ctx.rotate(this.totation);//旋转
            ctx.scale(this.scaleX,this.scaleY);//缩放效果
            //绘画
            ctx.lineWidth=this.lineWidth;
            ctx.fillStyle=randomColor();//this.color;
            ctx.beginPath();
            ctx.arc(0,0,this.radius,0,Math.PI*2,true);
            ctx.closePath();//关闭路径
            ctx.fill();//实现填充
            if(this.lineWidth>0){
                ctx.stroke();
            }
            //释放
            ctx.restore();
        }
        function randomColor(){
            var rgb='#';
            for(var i=0;i<3;i++){
                rgb+=xl(parseInt(Math.random()*256).toString(16));
            }
            function xl(r){
                if(r.length==1) r='0'+r;
                return r;
            }
            return rgb;
        }```
點擊查看更多內容
7人點贊

若覺得本文不錯,就分享一下吧!

評論

作者其他優質文章

正在加載中
Web前端工程師
手記
粉絲
10
獲贊與收藏
363

關注作者,訂閱最新文章

閱讀免費教程

感謝您的支持,我會繼續努力的~
掃碼打賞,你說多少就多少
贊賞金額會直接到老師賬戶
支付方式
打開微信掃一掃,即可進行掃碼打賞哦
今天注冊有機會得

100積分直接送

付費專欄免費學

大額優惠券免費領

立即參與 放棄機會
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號

舉報

0/150
提交
取消