Canvas入門-利用Canvas畫國旗

在這以前

須要你懂得如下方法的使用:javascript

  • beginPath()html

  • moveTo()java

  • lineTo()canvas

  • closePath()segmentfault

具體用法能夠參考個人上一篇文章 canvas入門-利用canvas製做一個七巧板瀏覽器

矩形的繪製

canvas提供了三種繪製矩形的方法:函數

  • fillRect(x, y, width, height)ui

    繪製一個填充的矩形
  • strokeRect(x, y, width, height)spa

    繪製一個矩形的邊框
  • clearRect(x, y, width, height)code

    清除制定矩形區域啊

上面方法的參數裏 x 和 y 分別爲相對於canvas原點的座標,width 和 height 設置了矩形的尺寸。
舉個栗子:

window.onload = function(){
    var canvas = document.getElementById("canvas");
    var ctx = canvas.getContext("2d");
    canvas.width = 900;
    canvas.height = 600;
    //繪製矩形
    ctx.fillRect(0,0,300,300);
    ctx.strokeRect(5,200,200,200);
    ctx.clearRect(0,0,100,100);
};

上面代碼先取得canvas對象上下文,接着繪製了一個填充矩形和邊框矩形,並清除了一個矩形區域。

繪製五角星以前

在這以前,須要分析五角星各個頂點的位置,以及弧度,因爲數學水平有限,都怪當初很差好學 T.T

clipboard.png

  • x:cos(18+i72)r //肯定 x 座標值

  • y:-sin(54+i72)r //肯定 y 座標值

  • 角度化 num/180*Math.PI //js將數值角度化的轉換公式

  • 400是圓的圓心點,若是不加400,則圓心點爲0,0

下面爲繪製五角星的函數,有五個參數:ctx:繪圖環境,R:大圓半徑,x:x座標值, y:y座標值, rot:旋轉角度

function drawStar(ctx,R,x,y,rot){
    ctx.beginPath();
    for (var i = 0; i < 5; i++ ) {
        ctx.lineTo(Math.cos((18+i*72-rot)/180*Math.PI)*R + x,-Math.sin((18+i*72-rot)/180*Math.PI)*R + y);
        ctx.lineTo(Math.cos((54+i*72-rot)/180*Math.PI)*R/2.4 + x,-Math.sin((54+i*72-rot)/180*Math.PI)*R/2.4 + y);
    };
    ctx.closePath();
    ctx.fill();
}

下面貼上完整代碼:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>canvas</title>
</head>
<body>
    <canvas id="canvas" style="border: 1px solid #aaa; display: block; margin: 50px auto">
        當前瀏覽器不支持cnavas        
    </canvas>
<script type="text/javascript">
window.onload = function(){
    var canvas = document.getElementById("canvas");
    var ctx = canvas.getContext("2d");
    //繪製中國國旗
    ctx.fillStyle = "red";
    ctx.fillRect(0,0,900,600);
    //繪製五角星
    //x:cos(18+i*72)*r
    //y:-sin(54+i*72)*r
    //角度化 num/180*Math.PI
    //依次制定大圓和小圓的一個點
    //400是圓的圓心點,若是不加400,則圓心點爲0,0
    ctx.fillStyle = "yellow";
    drawStar(ctx, 60, 120, 160, 0);
    var starF = [35, 5, 335, 305];
    for (var j = 0; j < starF.length; j++){
        var rot = 18 + j * 15;
        var x = Math.cos( starF[j]/180 * Math.PI ) * 180 + 120;
        var y = -Math.sin( starF[j]/180 * Math.PI ) * 180 + 160;
        drawStar(ctx, 60/2.4, x, y, rot);
    }
};
function drawStar(ctx,R,x,y,rot){
    ctx.beginPath();
    for (var i = 0; i < 5; i++ ) {
        ctx.lineTo(Math.cos((18+i*72-rot)/180*Math.PI)*R + x,-Math.sin((18+i*72-rot)/180*Math.PI)*R + y);
        ctx.lineTo(Math.cos((54+i*72-rot)/180*Math.PI)*R/2.4 + x,-Math.sin((54+i*72-rot)/180*Math.PI)*R/2.4 + y);
    };
    ctx.closePath();
    ctx.fill();
}
</script>
</body>
</html>

最後效果爲:

clipboard.png

相關文章
相關標籤/搜索