HTML5css3學習總結(4)canvas繪圖

來源:互聯網
上載者:User

標籤:sel   number   隨機函數   context   dex   圖形   注意   ext   解決   

canvas HTML5 重中之重

canvas是HTML5中的重點;今天簡單的學習了一下,總結一下canvas的概念;canvas是要有物件導向的思維;各個標籤就像我們畫水彩畫一樣,需要注意標籤使用的順序
canvas就是一個畫布;可以畫線,圖形,填充等。操作圖片和文本。操作方式是使用js;可以提供2d圖形,3d圖形繪製;


canvas使用:
①<canvas id=‘myCanvas‘ width=‘500‘ height=‘500‘></canvas>
需要有一個ID ,畫布的尺寸;
②通過ID擷取canvas的Dom對象,擷取context;
var canvasDom=document.getElementById(‘canvas‘)
var context=canvasDom.getContext(‘2d‘)
操作context兩種預設:1,繪製線(stroke)2,填充(fill);
moveTO(x,y)移動x,y
lineTo(x,y)連線至x ,y
stroke();描邊;
lineWidth:繪製出的線粗細;
fillRect(x,y,width,height)填充矩形;
clearRect(x,y,width,height)清除畫布地區;清除重複繪製的現象
beginPath-->開闢新路徑;
closePath--->閉合路徑;
stroke()--->描邊;
fill();--->>填充;
lineWidth---》線寬;
lineJoin----->連接點樣式;
lineCap------>線頭樣式;
strokeStyle--->描邊顏色;
fillStyle------->填充顏色;

 

繪製直線

<body><canvas id="myCanvas" width="500" height="500"></canvas><script>    var oCanvas=document.querySelector(‘canvas‘)    var ctx=myCanvas.getContext(‘2d‘)    ctx.moveTo(x,y)//x,y座標        ctx.lineTo(x,y)//繪製到x,y這個位置        ctx.lineWidth=‘10‘//繪製線寬10px;        ctx.strokeStyle=‘red‘//繪製線顏色        ctx.fillStyle=‘blue‘//填充顏色        ctx.stroke()//描邊        ctx.fill()//</script></body>

繪製矩形

<body><canvas id="myCanvas" width="500" height="500"></canvas><script>    var oCanvas=document.querySelector(‘canvas‘)    var ctx=myCanvas.getContext(‘2d‘)    ctx.strokeStyle=‘red‘;    ctx.strokeRect(10,10,190,100)//繪製矩形接收4個參數。x,y,width,height    ctx.fillStyle=‘blue‘    ctx.fillRect(110,110,100,100)</script>

繪製圓

<canvas id="mycanvas" width="500" height="500"></canvas><script>    var oCanvas=document.querySelector(‘#mycanvas‘)    var ctx=oCanvas.getContext(‘2d‘)    ctx.beginPath();//開新路徑    //繪製圓接收參數圓心X座標,圓心y座標,半徑,開始角度 結束角度 是否逆時針;    ctx.arc(250,250,100,0,Math.PI*2,true)    ctx.fillStyle=‘red‘    ctx.fill();        ctx.closePath();//閉合路徑    //左眼    ctx.beginPath();    ctx.arc(200,230,10,0,Math.PI*2,true)    ctx.fillStyle=‘black‘    ctx.fill();    ctx.closePath();    //右眼    ctx.beginPath();    ctx.arc(300,230,10,0,Math.PI*2,true)    ctx.fillStyle=‘black‘    ctx.fill();    ctx.closePath();    //嘴    ctx.beginPath();    ctx.arc(250,270,50,0,Math.PI,false)    ctx.fillStyle=‘yellow‘    ctx.fill();        ctx.closePath();</script>

 

<body>    <canvas width="600" height="300"></canvas>    <script>        var oCanvas = document.querySelector(‘canvas‘);        var ctx = oCanvas.getContext(‘2d‘);        ctx.fillStyle = ‘rgba(12,32,212,0.4)‘             //添加資料        var data = [            rnd(100,1000),rnd(100,1000),rnd(100,1000),rnd(100,1000),rnd(100,1000)        ];        var max = Math.max.apply(null,data);               //迴圈資料        data.forEach(function(number,index){            var {                height,                width            } = oCanvas;            var h = number/max*height            var w = index*width/data.length            ctx.fillRect(w,height-h,60,h);        })        function rnd(n,m){            return parseInt(Math.random()*(m-n)+n)        }    </script></body>

 

自己試了一個小方法下載自己繪製的圖片

//在body裡添加一個點擊按鈕,在點擊的時候建立一個a標籤,並更改a標籤的href屬性,使用canvas上的toDataURL方法;var oBtn=document.querySelector(‘button‘);    oBtn.onclick=function(){        var oA=document.createElement(‘a‘)        oA.href=oCanvas.toDataURL();        oA.download=‘資料圖.png‘        oA.click();        }

 

就總結到這裡吧,自己後來又寫了一個小例子鞏固一下所學的知識;貼上代碼歡迎大家指正,畢竟我還是那麼low。

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><title>無標題文檔</title><style>    body{         background:#000;        }    canvas{background:#FFF;}</style></head><body><canvas id="mycanvas" width="1300" height="800"></canvas><script>    var oCanvas=document.querySelector(‘#mycanvas‘)    var ctx=oCanvas.getContext(‘2d‘)    var speed=4    var angle=0    var n=0    setInterval(function(){        ctx.clearRect(0,0,oCanvas.width,oCanvas.height)        ctx.beginPath();        ctx.moveTo(n,250)        ctx.arc(n,250,20,d2r(angle),d2r(360-angle),false)        n++;        ctx.fillStyle=‘pink‘        ctx.closePath();        ctx.stroke();        ctx.fill();        angle+=speed        if(angle > 45 || angle<0 ){            speed*=-1            }        },16)        //度數轉換為弧度    function d2r(degree){        return degree/180*Math.PI;        }</script></body></html>

這是一個貪吃豆的頭像,只做到了嘴閉合後面自己在把遊戲效果寫出來;

 

 

 

 

這個是一個稍微複雜的屏保問題,電腦原因沒辦法刪除gif圖片,有興趣的朋友可以複製代碼在電腦上查看效果,裡面注釋已經白話的low死;希望不要嘲笑;

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><title>無標題文檔</title><style>        body{            background-color: #182327;            margin: 0;        }    </style></head><body>    <canvas width="1300" height="800"></canvas>    <script>        var oCanvas=document.querySelector(‘canvas‘)        var ctx=oCanvas.getContext(‘2d‘)        var amount=200;//建立點的個數        var arr=[];//定義一個數組存每個點移動的資料;                var range=100;        var first=true;        //迴圈建立移動的點        for( var i=0;i<amount;i++){            arr.push({                x:rnd(0,oCanvas.width),                y:rnd(0,oCanvas.height),                speedX:rndSign()*rnd(1,3)*0.5,                speedY:rndSign()*rnd(1,3)*0.5,                r:rnd(1,4)                                })            }        setInterval(function(){            //先清除畫布地區;解決重複繪製的問題            ctx.clearRect(0,0,oCanvas.width,oCanvas.height);            arr.forEach(function(dot,index){                //開始繪製圖形                ctx.beginPath();                ctx.fillStyle=‘rgb(141,134,32)‘;                var {                    x,                    y,                    r,                    speedX,                    speedY                    }=dot;                    ctx.arc(x,y,r,0,2*Math.PI,false);                ctx.fill();                dot.x+=speedX;                dot.y+=speedY;                //限定點移動的範圍                if(dot.x<0||dot.x>oCanvas.width-r){                    dot.speedX*=-1                    }                                if(dot.y<0||dot.y>oCanvas.height-r){                    dot.speedY*=-1                    }            })        //    arr.forEach(function(dot,index){        for(let i=index;i<arr.length;i++){            //求出兩點之間距離,用於判斷是否連線            var distance = Math.sqrt(            Math.pow(dot.x - arr[i].x,2)+            Math.pow(dot.y - arr[i].y,2)        )                    //判斷什麼時候連線            if(distance<range){                ctx.beginPath();                ctx.moveTo(dot.x,dot.y);                ctx.lineTo(arr[i].x,arr[i].y);                ctx.strokeStyle=`rgba(141,134,32,${1-distance/range})`;                ctx.stroke();                }        }        });        },16);        //當滑鼠移動上去點跟著走        document.onmousemove=function({clientX,clientY}){                  //判斷第一次移上去            if(first){                first=false;                arr.push({                    x:clientX,                    y:clientY,                    speedX:0,                    speedY:0,                    r:1                    })                }else{                arr[0].x=clientX;                arr[0].y=clientY;                }        }        //隨機函數        function rnd(n,m){            return parseInt(Math.random()*(m-n)+n)        }        //解決點移動方向函數        function rndSign(){            return Math.random() > 0.5 ? 1 : -1;        }    </script></body></html>

 

HTML5css3學習總結(4)canvas繪圖

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.