h5學習-canvas繪製矩形、圓形、文字、動畫

繪製矩形
<!
DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>canvas繪製矩形</title> <script type="text/javascript" src="canvas.js"></script> <style type="text/css">//讓矩形顯示置頂 body{ margin: 0; padding: 0; } </style> </head> <body onload="draw('canvas');"> <canvas id = "canvas" width="500" height="350"></canvas> </body> </html>

//canvas.js
function
draw(id){ var canvas = document.getElementById(id); var context = canvas.getContext('2d'); context.fillStyle = "#000"; context.strokeStyle = "#f60"; context.lineWidth = 5; context.fillRect(0,0,500,350); context.strokeRect(50,50,180,120); }

繪製一個矩形:
1。獲取canvas元素 getElementById()
2。取得上下文 getContext()
3。填充與繪製邊框 fill() stroke()
4。設置繪製樣式 fillStyle stokeStyle 屬性
5。指定畫筆寬度 getcontext().linewidth
6。設置顏色值 經過第4步的屬性來設置
7。繪製矩形 context.fillRect(x,y,width,height)
context.strokeRect(x,y,width,height)
 
  繪製圓形:
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>canvas繪製圓形</title>
    <script type="text/javascript" src="canvas.js"></script>
    <style type="text/css">
        body{
            margin: 0;
            padding: 0;
        }
    </style>
</head>
<body onload="draw('canvas');">
<canvas id = "canvas" width="500" height="500"></canvas>
</body>
</html>
function draw(id){
    var canvas = document.getElementById(id);
    var context = canvas.getContext('2d');
    context.fillStyle = "#f1f2f3";
    context.fillRect(0,0,500,500);//背景的繪製

    for(var i = 0;i<10;i++){
        context.beginPath();
        context.arc(25*i,25*i,10*i,0,Math.PI*2,true);
        context.closePath();
        context.fillStyle = "rgba(255,0,0,0.25)";
        context.fill();
    }


}

效果圖;javascript

繪製一個圓形:
1。建立開始路徑,context.beginPath()
2.建立圖形路徑,context.arc(x,y,radius,starAngle,endAngle,anticlockwise);
var radius = degress*Math.PI/180, Math.PI=180度
anticlockwise 是否順時針
3.建立完成關閉路徑,context.clasePath()
4。設置繪製樣式而後調用繪製方法進行繪製,context.filllStyle = 'rgba(255,0,0,0.25)';context.fill();
 
 
繪製文字:
function draw(id){
    var canvas = document.getElementById(id);
    var context = canvas.getContext('2d');
    context.fillStyle = "#a0f";
    context.fillRect(0,0,800,300);//背景的繪製


    context.fillStyle = "#fff";//文字的顏色
    context.strokeStyle = "#fff";

    context.fillText("小檸檬呢",50,50);
    context.strokeText("小小的檸檬",50,100);

 

繪製動畫css

var i;
function draw(id){
    var canvas = document.getElementById(id);
    context = canvas.getContext('2d');
    setInterval(painting,100);//設置動畫的間隔時間。第一個參數表示執行動畫的函數,第二個函數 間隔時間
    //經過不斷地變化xy座標來實現動畫效果。clearRect(),將畫布總體或者局部擦除。
    i=0;
}


function painting(){
    context.fillStyle = "#f00";
    context.fillRect(i,0,10,10);
    i=i+20;
}
相關文章
相關標籤/搜索