Home > Web Front-end > H5 Tutorial > body text

HTML5 Canvas drawing example tutorial

PHPz
Release: 2017-04-23 10:20:39
Original
1606 people have browsed it

This article explains in detail how to use HTML5 Canvas drawing for reference and learning by PHP Chinese netizens

First of all, please note: <canvas>## The # element is not supported by some older browsers, but is supported by Firefox 1.5+, Opera 9+, newer versions of Safari, Chrome, and Internet Explorer 9.

requires first Obtain the 2D rendering context to draw the element

var canvas = document.getElementById('canvas');var ctx = canvas.getContext('2d');
Copy after login

Canvas draws images based on state. <span style="font-family: verdana, Arial, Helvetica, sans-serif;"></span>

Basic usage:


1. Use the following two methods to define a path

context.moveTo(x,y); //起点context.lineTo(x,y); //连线到终点
Copy after login

2. For multiple Paths, if you want to process them separately, you need to add the following two methods at the beginning and end of the path definition to separate them

context.beginPath();
context.closePath();
Copy after login

3. Path style

context.lineWidth    //定义线条宽度context.strokeStyle    //定义线条颜色context.fillStyle    //填充颜色context.stroke();    //绘制线条context.fill();        //绘制填充的颜色块
Copy after login

4. Draw an arc


context.arc(
    centerx, centery, radius,    //圆心坐标(x,y)以及半径r
    startingAngle, endingAngle,    //开始的弧度值,和结束的弧度值
    anticlockwise = false        //可选参数,(false顺时针绘制)还是(true逆时针绘制))
Copy after login

5. Draw a rectangle


context.rect(x, y, width, height); //设置矩形状态context.fill();
context.stroke();//或者context.fillRect(x, y, width, height); //绘制填充的矩形context.strokeRect(x, y, width, height); //绘制边框的矩形
Copy after login

6.Format of attribute values ​​of fillStyle and strokeStyle


#FFF
#333rgb(255,128,0)
rgba(100,100,100,0.8)
hsl(20,62%,28%)
hsla(40,83%,33%,0.6)
red
Copy after login

7. Line Cap: lineCap is used to set the shape of both ends of the line. It has the following three values:


butt(default)    //默认缺省round    //圆头square    //方头context.lineCap = "round";
Copy after login

8. The shape of intersection between lines: lineJoin Three attribute values:


miter(default)    //尖角bevel    //斜接round    //圆角context.lineJoin = "round";//当尖角很尖锐时,会出现lineJoin为bevel//此时跟另外一个属性有关:miterLimit,默认值是10//当在lineJoin为miter情况下,miterLimit大于10时,lineJoin会自动变成bevel
Copy after login

9. Image transformation and state savingImage transformation:


位移:translate(x,y);
旋转:rotate(deg);
缩放:scale(sx,sy);//保存当前图形状态:context.save();//恢复图形的所有状态:context.restore();//使用:context.save();
context.translate(x,y);
context.restore();
Copy after login

10. Transformation matrix


a    c    e
b    d    f0    0    1a水平缩放(1)
b水平倾斜(0)
c垂直倾斜(0)
d垂直缩放(1)
e水平位移(0)
f垂直位移(0)
即:默认时,该变换矩阵为单位阵//设置变换矩阵transform(a,b,c,d,e,f);//重置变换矩阵setTransform(a,b,c,d,e,f);
Copy after login

11. Linear gradient


var grd = context.createLinearGradient(xstart,ystart,xend,yend);//开始坐标到结束坐标grd.addColorStop(stop,color);//stop为浮点数,开始坐标点到结束坐标点直线上,某个位置(0.0~1.0之间)//例:var skyStyle = context.createLinearGradient(0,0,800,800);
skyStyle.addColorStop(0.0, 'black');
skyStyle.addColorStop(1.0, 'blue');

context.fillStyle = skyStyle;
Copy after login

12. Radial gradient


var grd = context.createRadialGradient(x0,y0,r0,x1,y1,r1);//开始圆心坐标到结束圆心坐标,以及半径grd.addColorStop(stop,color);//stop为浮点数,开始坐标点到结束坐标点直线上,某个位置(0.0~1.0之间)
Copy after login

13. Image filling


createPattern(img,repeat-style) //img为图片对象,repeat-style填充格式//其中repeat-style: no-repeat/repeat-x/repeat-y/repeat//例:var backgroundImage = new Image();
backgroundImage.src = "bg.jpg";
backgroundImage.onload = function(){var pattern = context.createPattern(backgroundImage,"repeat");
context.fillStyle = pattern;
context.fillRect(0,0,800,800);
}
Copy after login

14.Canvas filling


createPattern(canvas,repeat-style) //canvas对象,repeat-style填充格式
Copy after login

Example:


    window.onload=function(){        var canvas=document.getElementById("canvas");
        canvas.width=800;
        canvas.height=800;        var context=canvas.getContext("2d");        var backCanvas=createBackgroundCanvas();        var pattern=context.createPattern(backCanvas,"repeat");
        context.fillStyle=pattern;
        context.fillRect(0,0,800,800);
   }    function createBackgroundCanvas(){        var backCanvas=document.createElement("canvas");
        backCanvas.width=100;
        backCanvas.height=100;        var backContext=backCanvas.getContext("2d");
        backContext.beginPath();
        backContext.moveTo(15,15);
        backContext.lineTo(50,50);
        backContext.lineWidth=10;
        backContext.strokeStyle="green";
        backContext.stroke();        return backCanvas;
    }
Copy after login

15.video filling


createPattern(video,repeat-style) //video视频对象
Copy after login

16. Another arc drawing method


context.arcTo(
    x1,y1,x2,y2,    //x1,y1,x2,y2两个坐标与起始点x0,y0组成一个角
    radius    //半径)
Copy after login

Example:


context.moveTo(x0,y0);
context.arcTo(x1,y1,x2,y2,R);//起始点为(x0,y0),该弧线与01线以及12线相切
Copy after login

17. Bezier CurveBezier Quadratic Curve

context.moveTo(x0, y0);    //起始点context.quadraticCurveTo(
    x1, y1,    //控制点坐标
    x2, y2    //终点坐标)
Copy after login
Bezier Cubic Curve

context.moveTo(x0, y0);    //起始点context.bezierCurveTo(
    x1, y1, //控制点坐标
    x2, y2, //控制点坐标
    x3, y3  //终点坐标)
Copy after login

18. Text rendering

context.font = "font-style font-variant font-weight font-size font-family";    //css字体样式,默认值:"20px sans-serif"context.fillText(String, x, y, [maxlen]);    //String字符串,和坐标位置,第四个为可选参数,这行文字的最长宽度context.strokeText(String, x, y, [maxlen]);    

font-style: normal    (Default)
            italics   (斜体字)
            oblique   (倾斜字体)

font-variant: normal  (Default)
              small-caps    (小写英文字母变成小的大写字母)

font-weight: normal   (Default)
             lighter
             bold
             bolder             100,200,300,400(normal)             500,600,700(bold)             800,900font-size:  20px (Default)
            2em            150%font-family: 设置多种字体备选,支持@font-face
Copy after login
Text horizontal alignment:


context.textAlign = left
                    right
                    center
Copy after login
Vertical alignment of text:


context.textBaseline =  top
                        middle
                        bottom
                        alphabetic (Default)
                        ideographic
                        hanging
Copy after login

Metrics of text:


context.measureText(String).width //获取渲染的字符串的宽度
Copy after login

19. Shadow

context.shadowColor    //阴影颜色context.shadowOffsetX    //阴影的位移值context.shadowOffsetY
context.shadowBlur    //阴影模糊度
Copy after login

20. Global method:

context.globalAlpha = 1 (Default)    //全局透明度,默认不透明context.globalCompositeOperation = "source-over" (Default) //绘制的图像在重叠的时候的效果,默认是(source-over)后面绘制的图像覆盖前面绘制的图像"source-atop"    //后面绘制的图像覆盖前面绘制的图像,但后面的图像只显示重叠部分"source-in"    //后面绘制的图像覆盖前面绘制的图像,但只显示重叠部分"source-out"    //只显示后绘制的图像,而且重叠部分被切掉"destination-over"    //前面绘制的图像覆盖后面绘制的图像"destination-atop"    //前面绘制的图像覆盖后面绘制的图像,但前绘制的图像只显示重叠部分"destination-in"    //前面绘制的图像覆盖后面绘制的图像,但只显示重叠部分"destination-out"    //只显示前绘制的图像,而且重叠部分被切掉"lighter"    //重叠部分颜色叠加融合"copy"    //只显示后绘制图像"xor"    //异或,重叠部分被挖空
Copy after login

21. Clip area Method to set the currently created path as the current clipping path

void ctx.clip();void ctx.clip(fillRule);void ctx.clip(path, fillRule);
Copy after login

fillRule

This algorithm determines whether a point is within the path or within outside the path.

path

The Path2D path that needs to be cut.

Example:

ctx.arc(100, 100, 75, 0, Math.PI*2, false);
ctx.clip();
ctx.fillRect(0, 0, 100,100);
Copy after login

22. Non-zero wrapping principle Path direction
Application: Hollow paper-cut effect

23.canvas interaction

context.clearRect(x,y,width,height) //清空指定的区域context.isPointInPath(x,y) //点击检测函数,该点是否在当前规划路径内,当检测点包含在当前或指定的路径内,返回 true;否则返回 false//以下两个是获取鼠标点击在canvas坐标var x = event.clientX - canvas.getBoundingClientRect().left;var y = event.clientY - canvas.getBoundingClientRect().top;
Copy after login

24. Extend the context of CanvasExtend the drawStar method to context:

CanvasRenderingContext2D.prototype.drawStar = function(){}
Copy after login

25.Canvas compatibility Detection

<canvas id="canvas">当前浏览器不支持Canvas,请更换浏览器再试</canvas>
Copy after login

Compatibility issues between Canvas and IE6, 7, and 8 browsers

Introducing the explorecanvas library:

https://code.google.com/p/explorecanvas/<!--[if IE]><script type="text/javascript" src="../excanvas.js"></script><![endif]-->
Copy after login

26. canvas graphics library: canvasplus || artisanJS || RGraph

code.google.com/p/canvasplus

artisanjs.com

roopons.com. au/wp-content/plugins/viral-optins/js/rgraph

27. Canvas API interface document:

developer.mozilla.org/zh-CN /docs/Web/API/CanvasRenderingContext2D

The above is the detailed content of HTML5 Canvas drawing example tutorial. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!