日期:2014-05-17  浏览次数:20915 次

HTML5(二)basic drawing
HTML5(二)basic drawing

1.coordinate
(0,0) is at the top and left corner of canvas.

2. Stroke and Fill
Stroke
line, the picture are base on the lines.

Fill
area filled with something.

We can see the difference in StrokeRect and FillRect. My page test2.html is:

<canvas id="test2" width="200" height="200" style="background-color: grey">
your browser does not support this.
</canvas>
<input type="button" value="strokeRect"  onclick="strokeRect();"/>
<input type="button" value="fillRect"  onclick="fillRect();"/>

<script type="text/javascript">
function strokeRect(){
    var canvas = document.getElementById('test2');
    var ctx=canvas.getContext("2d");
   
    ctx.clearRect(0,0,200,200);
    ctx.strokeStyle="blue";
    ctx.strokeRect(10,10,180,180);
}

function fillRect(){
    var canvas = document.getElementById('test2');
    var ctx=canvas.getContext("2d");
   
    ctx.clearRect(0,0,200,200);
    ctx.fillStyle="blue";
    ctx.fillRect(10,10,180,180);
}
</script>

3.Color
stokeStyle is the css of line.
fillStyle is the css of fill area.

4.Basic drawing method
moveTo(x,y): move the pen to the position (x,y)

lineTo(x,y):    draw a straight line from current position to (x,y)

arc(x,y,radius,startAngle,endAngle,anticlockwise): draw a arc.

quadraticCurveTo(cp1x,cp1y,x,y)
bezierCurveTo(cp1x,cp1y,cp2x,cp2y,x,y): read doc.

rect(x,y,width,height): rectangle

5.Drawing Path
beginPath(): start to draw to context(in memory, do not display in the screen)
stroke():      all the lines will displayed in the screen
closePath(): This method is not nessary and it will give the picture a occlusion line.
fill():            give the picture a occlusion line and the fill the picture

all the fill style picture have not drawing path, they display in the screen immediately.

my example test2-2.html is :
<canvas id="test2" width="200" height="200" style="border:1px solid #c3c3c3;">
update your browser, please.
</canvas>
<input type="button" value="draw"  onclick="drawTri();"/>
<input type="button" value="clean"  onclick="clearTri();"/>

<script type="text/javascript">
    function drawTri(){
        var canvas = document.getElementById('test2');
        var ctx=canvas.getContext("2d");
       
        ctx.beginPath();
        ctx.moveTo(75,50);
        ctx.lineTo(100,75);
        ctx.lineTo(100,25);
        ctx.fill();
    }
    function clearTri(){
        var canvas = document.getElementById('test2');
        var ctx=canvas.getContext("2d");
        ctx.clearRect(0,0,200,200);
    }
</script>

6.draw the grid
my example test2-3.html is like this:
<canvas id="test3" width="500" height="375" style="border:1px solid #c3c3c3;">
old browser.update right now!