Canvas绘图

<canvas>由几组API构成,但并非所有浏览器都支持所有这些API,除了具备基本绘图能力的2D上下文,<canvas>还建议了一个名为WebGL的3D上下文。

基本用法:先设置width和height属性,调用getContext()方法并传入上下文的名字,如果传入2d,就可以取得2D上下文对象。如:

    <canvas id="drawing" width="200" height="200">A drawing of something.</canvas>
    var drawing=document.getElementById("drawing");
    //确定浏览器支持<canvas>元素
    if(drawing.getContext){
    var context=drawing.getContext("2d");
}

使用2D上下文的方法,我们可以绘制简单的2D图形,比如矩形、弧线和路径。2D上下文两种基本绘图操作是填充和描边。取决于两个属性fillStyle和strokeStyle.

矩形绘制(三种方法):fillRect(),strokeRect(),clearRect()

fillRect()方法在画布上绘制的矩形会填充制定的颜色,通过fillStyle方法来实现。strokeRect()方法在画布上绘制的矩形会使用指定的颜色描边,描边颜色通过strokeStyle属性制定。clearRect()方法用于清楚画布上的矩形区域。

需要注意的是,用fillRect()方法的时候我们可以填充矩形,用strokeRect()时我们可以给矩形描边,但是不可以混用这两种属性和方法,比如给fillRect()方法赋strokeStyle值,fillRect()方法会不认识这个属性,进而显示默认的黑色。如下:

    var drawing=document.getElementById("drawing");
    if(drawing.getContext){
    var context=drawing.getContext("2d");
    context.strokeStyle="#FF9966";
    context.fillRect(10,10,50,50);
    context.fillStyle="#00f";
    context.fillRect(30,30,50,50);
    context.strokeStyle="#FF9966";
    context.strokeRect(40,40,50,50);
    context.clearRect(40,40,10,10);
}

结果是这样: _config.yml

第一个矩形不认识strokeStyle值,所以显示了黑色。另外,样式一般都写在方法的前面的。clearRect()除外。

Written on December 17, 2016