HTML5css3學習總結(4)canvas繪圖


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>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM