Home  >  Article  >  Web Front-end  >  Detailed explanation of the sample code of html5 Canvas drawing (1)

Detailed explanation of the sample code of html5 Canvas drawing (1)

黄舟
黄舟Original
2017-03-28 15:34:041542browse

Only with a strong foundation in drawing, coloring, and transforming basic two-dimensional graphics can we use Canvas more effectively;

Below, I will briefly understand how canvas draws basic shapes (rectangle, straight line, arc, Bezier curve), etc.;

First post all the following related The basic code segment to implement operation:

Base code

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8" />
        <script type="text/javascript" src="modernizr-latest.js"></script>
        <script type="text/javascript">
            window.addEventListener("load", eventWindowLoaded, false);
            var Debugger = function() {};
            Debugger.log = function(message) {
                try {
                    console.log(message);
                } catch (exception) {
                    return;
                }
            }
            
            function eventWindowLoaded() {
                canvasApp();
            }

            function canvasSupport() {
                return Modernizr.canvas;
            }

            function canvasApp() {
                //是否支持CANVAS判断
if(!canvasSupport()) {
                    return;
                }
                //取Canvas
var theCanvas = document.getElementById("canvasOne");
                //获取绘图环境context
var context = theCanvas.getContext("2d");
                //绘图方法的实现
function drawScreen() {}
                //绘图方法调用执行
                drawScreen();
            }
        </script>
    </head>
    <body>
        <div style="position: absolute; top: 50px; left: 50px; border:1px solid #0000ff">
            <canvas id="canvasOne" width="550" height="400">
                Your browser does not support HTML5 Canvas.
            </canvas>
        </div>
    </body>
</html>

For all the following example codes, just replace the above function drawScreen()!

Basic Rectangle Shape (rectangle)

In Canvas, there are three ways to draw a rectangle: filling (), stroking(), or clearing

The three methods correspond to the following three methods (the parameters are all the same, which are the coordinates [x, y] of the upper left corner of the rectangle, the Width, height of rectangle):


    1. #fillRect(x,y,width,height): fill the rectangular area;

    2. ##strokeRect(x,y,width,height): draw A rectangular border;

    3. ##clearRect(x,y,width,height): Clear the specified rectangular area and make the area transparent;
Example

function drawScreen() {
context.fillStyle = &#39;#000000&#39;;//填充颜色
context.strokeStyle = &#39;#00ff00&#39;;//轮廓颜色
context.lineWidth = 2;//线宽
context.fillRect(10, 10, 40, 40);//填充矩形
context.strokeRect(7, 7, 46, 46);//画矩形轮廓
context.clearRect(20, 20, 20, 20);//清除矩形区域
}
上一篇有提到Current state;
当我们在绘画时,我们可以利用所谓的绘画状态的堆栈,
对于canvas context在任何一个时间的数据的每一个状态都会存储;
下面是对于每一个状态,存储在堆栈中的一个数据列表;
变换矩阵(旋转、移动、缩放等);
剪切区域;
Canvas特征的当前值(部分):
 — globalAlpha
— globalCompositeOperation
 — strokeStyle
— textAlign, textBaseline
— lineCap, lineJoin, lineWidth, miterLimit
— fillStyle
— font
— shadowBlur, shadowColor, shadowOffsetX, and shadowOffsetY
在绘图环境中,正在操作的当前path and 当前位置并不是状态的一部分;Importmant!!!
如何保存恢复当前的状态呢?
context.save()---push to stack;
context.restore()---pop form stack;
先有一个简单的印象,之后会更加详细的剖析;


Create Lines(直线) 

利用path来创建线(line)

Path:用来画出一系列的相连的圆弧或者线条,可以称之为“轨迹”,使用它可以画出任意复杂的形状;

一个Canvas Context仅有一个current path ;

在调用context.save()时,current path并不做为当前的状态(current state)存储于stack中;

利用.beginPath()功能方法来启动一个Path;

利用.closePath()功能方法来关闭一个Path;

Example:画一条10px宽度的水平直线

function drawScreen() {
    context.strokeStyle = "#000000";//线的颜色                    
    context.lineWidth = 10;//线的宽度
    context.beginPath();//启动path
    context.moveTo(20, 20);
    context.lineTo(100, 20);
    context.stroke();//绘画
    context.closePath();//关闭path
}

线的属性:lineCap
直线lineCap属性:线帽,也就是线两端的样式,只有绘制较宽的线的,它才有效;

有三个有效值:butt\round\square

"butt":默认值,指定了线段应该没有线帽。

"round":线段应该带有一个半圆形的线帽,半圆的直径等于线段的宽度,并且线段在端点之外扩展了线段宽度的一半。

"square":线段应该带有一个矩形线帽。这个值和 "butt" 一样,但是线段扩展了自己的宽度的一半。


Example

function drawScreen() {
context.strokeStyle = "#000000";//线的颜色                    
context.lineWidth = 10;//线的宽度
context.lineCap="butt";//butt\round\square
context.beginPath();//启动path
context.moveTo(20, 20);
context.lineTo(100, 20);
context.stroke();//绘画
context.closePath();//关闭path
                    
context.lineCap="round";//butt\round\square
context.beginPath();//启动path
context.moveTo(20, 40);
context.lineTo(100, 40);
context.stroke();//绘画
context.closePath();//关闭path
                    
context.lineCap="square";//butt\round\square
context.beginPath();//启动path
context.moveTo(20, 60);
context.lineTo(100, 60);
context.stroke();//绘画
context.closePath();//关闭path
}

线的属性:lineJoin

lineJoin属性:表示两条线段如何连接;

当一个路径包含了线段或曲线相交的交点的时候,用lineJoin 属性来说明如何绘制这些交点;

该属性也有三个有效值:miter bevel round

"miter":默认值,两条线段的外边缘一直扩展到它们相交

 "bevel":以一个斜边进行连接

"round":以一个圆弧边进行连接

    function drawScreen() {
    context.strokeStyle = "#000000";
    context.lineWidth = 10;    
    context.lineJoin = "miter";
    context.beginPath();
    context.moveTo(20, 20);
    context.lineTo(100, 20);
    context.lineTo(100, 40);
    context.stroke();    
    context.closePath();                    


    context.lineJoin = "bevel";
    context.beginPath();
    context.moveTo(20, 60);
    context.lineTo(100, 60);
    context.lineTo(100, 80);
    context.stroke();
    context.closePath();


    context.lineJoin = "round";
    context.beginPath();
    context.moveTo(20, 100);
    context.lineTo(100, 100);
    context.lineTo(100, 120);
    context.stroke();
    context.closePath();

    context.lineJoin = "miter";
    context.beginPath();
    context.moveTo(20, 140);
    context.lineTo(100, 140);
    context.lineTo(80, 180);
    context.stroke();    
    context.closePath();
}

Arcs(圆弧)

一段圆弧可以是一个完整的圆也可以圆的一部分;

生成圆弧:context.arc()

context.arc(x, y, radius, startAngle, endAngle, anticlockwise)

参数依次代表圆心,半径、起始角度、终止角度、圆弧的方向; 角度都是以弧度来表示;

anticlockwise为布尔类型 ;true为顺时针、false为逆时针

function drawScreen() {
context.strokeStyle = "black";
context.lineWidth = 5;
context.beginPath();
context.arc(100, 100, 20, (Math.PI / 180) * 0, (Math.PI / 180) * 360, false);
context.stroke();
context.closePath();

context.beginPath();
context.arc(100, 200, 20, (Math.PI / 180) * 0, (Math.PI / 180) * 90, false);
context.stroke();
context.closePath();

context.beginPath();
context.arc(100, 300, 20, (Math.PI / 180) * 0, (Math.PI / 180) * 90, true);
context.stroke();
context.closePath();
}

Bezier Curves(贝赛尔曲线)

Canvas支持二次 and 三次贝塞尔曲线的绘画

此处的贝塞尔曲线是定义在二维空间里的,需要一个起始点、一个终止点,再加上一个或者两个控制点来创建曲线;

控制点来决定所构造曲线的走向;

三次贝塞尔曲线需要两个点;

二次贝塞尔曲线需要一个点即可;

主要通过以下两个方法来绘画:

context.bezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y)

context.quadraticCurveTo(cpx, cpy, x, y)

二次贝塞尔曲线:
function drawScreen()
{
context.strokeStyle = "black";
context.lineWidth = 5;
context.beginPath();
context.moveTo(0, 0);
context.quadraticCurveTo(500, 25, 0, 100);
context.stroke();
context.closePath();
}
曲线的起始点为(0,0),结束点为(0,100)
点(500,25)控制最终生成曲线的走向;

三次贝塞尔曲线:
 function drawScreen()
 {
     context.strokeStyle = "black";
     context.lineWidth = 5;
     context.beginPath();
     context.moveTo(0, 0);
     context.bezierCurveTo(0, 125, 300, 175, 150, 300);
     context.stroke();
     context.closePath();
 }
 曲线的起点(0,0),结束点(150,300)
 (0, 125), (300, 175)这两个为控制点;
 大家可能自己运行一下代码,看看效果,此处就不贴图了。。

The above is the detailed content of Detailed explanation of the sample code of html5 Canvas drawing (1). For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn