Canvas基本知识点一:直线图形

1,059 阅读1分钟

一、基本概述

1、canvas默认情况下的宽度是300px,高是150px,定义 宽高,应该再HTML中定义,而不应该在css中定义。

2、canvas使用的是W3C坐标系,y轴正方向向下。

二、直线绘制

1、一条直线

cxt.moveTo(x1,y1);
cxt.lineTo(x2,y2);
cxt.stroke();

说明:

  • cxt为上下文环境对象context.
  • moveTo()方法是将画笔移到(x1,y1)上,然后开始绘制,lineTo()方法是从(x1,y1)开始画直线,一直画到坐标(x2,y2),然后stroke()进行连线。

2、多条直线

cxt.moveTo(x1,y1);
cxt.lineTo(x2,y2);
cxt.lineTo(x2,y2);
...
cxt.stroke();

说明:

第二次的lineTo(),canvas会以上一次的lineTo坐标作为调用的起点,然后开始画。

三、矩形

1、描边矩形

cxt.strokeStyle = 属性值
cxt.strokeRect(x,y,width,height);

说明

strokeStyle是context对象的一个属性,而strokeRect()是context对象的一个方法。

(1)strokeStyle属性有三种:颜色、渐变色、图案

cxt.strokeStyle = '#000';
cxt.strokeStyle = 'red';
cxt.strokeStyle = 'rgb(255,0,0)';
cxt.strokeStyle = 'rgba(255,0,0,0.6)';

(2)strokeStyle属性必须在strokeRect()方法之前定义,否则strokeStyle无效。

2、填充矩形

cxt.fillStyle = 属性值
cxt.fillRect(x,y,width,height);

说明:

fillStyle是context对象的一个属性,而fillRect()是context对象的一个方法。

(1)fillStyle属性有三种:颜色、渐变色、图案

cxt.fillStyle= '#000';
cxt.fillStyle= 'red';
cxt.fillStyle= 'rgb(255,0,0)';
cxt.fillStyle= 'rgba(255,0,0,0.6)';

(2)fillStyle属性必须在fillRect()方法之前定义,否则fillStyle无效。

3、rect()方法

cxt.rect(x,y,width,height);

(1)rect()和stroke()

cxt.strokeStyle = 'red';
cxt.rect(50,50,80,80);
cxt.stroke();

等同于:

cxt.strokeStyle = 'red'
cxt.strokeRect(50,50,80,80);

(2)rect()和fill()

cxt.fillStyle = 'red';
cxt.rect(50,50,80,80);
cxt.fill();

等同于:

cxt.fillStyle = 'red';
cxt.fillRect(50,50,80,80);

使用rect()方法后,在调用stroke()和fill()方法,才能绘制出来。

4、清空矩形

cxt.clearRect(x,y,width,height)


一些函数封装的实例,可以参考github.com/yxjz/Canvas