关于Canvas

canvas是HTML5新定义的标签,通过使用脚本(Javascript)来绘制图形,这解决了以往在网页绘图时需要通过网页与Flash交互的麻烦。canvas 拥有多种绘制路径、矩形、圆形、字符以及添加图像的方法
canvas默认情况下没有边框和内容,只是一个300150的画布,所以需要设置height与width,这里需要主要的是**可以通过html属性‘width’,‘height’来设置canvas的宽高,但最好不要通过 css 属性来设置宽高。因为通过 css 属性设置的宽高会使 canvas 内的图像按照 300150 时的比例放大或缩小**

创建canvas元素

<canvas id="canvas_1" width=“200” height="100"></canvas>

canvas的一些声明

在绘制之前需要在script中进行声明,通常我们可以在html文件中加入:

<script type="text/javascript">
var c=document.getElementById("canvas_1");    //首先找到我们之前的canvas
var cxt=c.getContext("2d");      //创建context对象
cxt.fillStyle="#FF0000";
cxt.fillRect(0,0,150,75);
</script>

其中getContext(),context是一个封装了很多绘图功能的对象,而getContext()是为了获取canvas的上下文环境,我们填入"2d"就是:getContext("2d") 对象是内建的 HTML5 对象,拥有多种绘制路径、矩形、圆形、字符以及添加图像的方法。

canvas的坐标

左上角为(0,0),宽度为x,高度为y,所以(x,y)的坐标值永远不可能为负值。可以访问这个

canvas绘制图像

有两种方式,第一种是context.fill(),在填充前要先使用 fillStyle 设置填充的颜色或者渐变,并且如果路径未关闭,那么 fill() 方法会从路径结束点到开始点之间添加一条线,以关闭该路径(正如 closePath() 一样),然后填充该路径。第二种是通过context.stroke(),通过 moveTo() 和 lineTo() 方法定义的路径。默认颜色是黑色。
两种方式在进行图形绘制前,都要设置好绘图的样式:

fillStyle()//填充的样式
strokeStyle()//边框样式
context.lineWidth()//图形边框宽度

绘制图形篇

绘制矩形

var canvas=document.getElementById('canvas');
var ctx=canvas.getContext('2d');
ctx.fillStyle='crimson';
ctx.fillRect(0,0,100,100);
ctx.strokeRect(120,0,100,100);

x是起始点的 x 坐标,y是起始点的 y 坐标,width是矩形的宽,height是矩形的高
其中fillRect是实心矩形,strokeRect是空心矩形

相应的,我们可以利用`clearRect(x,y,width,height)`来清除矩形区域 ### 圆形 context.arc(x, y, radius, starAngle,endAngle, anticlockwise) x : 圆心的 x 坐标 y:圆心的 y 坐标 radius : 半径 starAngle :开始角度 endAngle:结束角度 anticlockwise :是否逆时针(true)为逆时针,(false)为顺时针 ```html context.beginPath(); context.arc(300, 350, 100, 0, Math.PI * 2, true); //不关闭路径路径会一直保留下去 context.closePath(); context.fillStyle = 'crimson'; context.fill(); ``` ### 圆弧 ```html context.beginPath(); context.arc(600, 350, 100, 0, Math.PI , true); context.strokeStyle = 'crimson'; context.closePath(); context.stroke();

context.beginPath();
context.arc(300, 350, 100, 0, Math.PI , true);
context.strokeStyle = 'crimson';
//没有closePath
context.stroke();


### 线段
`moveTo(x,y)`:把路径移动到画布中的指定点,不创建线条
`lineTo(x,y)`:添加一个新点,然后在画布中创建从该点到最后指定点的线条
每次画线都从 moveTo 的点到 lineTo 的点。如果没有moveto,则第一个lineto视为起始点:
```html
    var canvas = document.getElementById('canvas');
    var ctx = canvas.getContext('2d');
    ctx.strokeStyle = 'crimson';
    ctx.fillStyle='blue';
    ctx.beginPath();
    ctx.lineTo(200,200);
    ctx.lineTo(200,100);
    ctx.lineTo(100,50);
    ctx.lineTo(200,200);
    ctx.closePath();
    ctx.fill();
    ctx.stroke();

线性渐变

var lg= context.createLinearGradient(xStart,yStart,xEnd,yEnd)
lg.addColorStop(offset,color)

xstart:渐变开始点x坐标
ystart:渐变开始点y坐标
xEnd:渐变结束点x坐标
yEnd:渐变结束点y坐标
offset:设定的颜色离渐变结束点的偏移量(0~1)
color:绘制时要使用的颜色
>

一个在做的项目的实例

原文地址:https://www.cnblogs.com/yunlambert/p/10043943.html