画布
### 前言:
html的canvas标签可以创建画布区域,使用js可以获取画布的上下文从而来设置画布及画布元素
### 2d画布绘制
## 1. 创建画布(html)
<canvas>
// 反馈html
<p>你的浏览器不支持canvas</p>
</canvas>
## 2. 设置画布尺寸
var canvas = document.querySelector('canvas');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
## 3. 调整html窗口(css)
/* 消除全窗口画布页面出现的滚动条 */
html,body{
margin:0;
over-flow:hidden;
}
## 4. 获取画布上下文
var ctx = canvas.getContext('2d') /* 2d表示2d画布类型 */
## 5. 设置画布背景色
/* 注意以下两行代码顺序不可逆 */
ctx.fillStyle = 'rgb(0,0,0)';
ctx.fillRect(0,0,canvas.width,canvas.height);
画布绘制元素
### 绘制矩形
## 1. 填充矩形
/* 该矩形为背景矩形 */
ctx.fillStyle = 'rgb(0,0,0)';
ctx.fillRect(0,0,canvas.width,canvas.height);
/* 绘制矩形 */
ctx.fillStyle = 'white';
ctx.fillRect(100,100,200,100);
## 2. 无填充矩形
ctx.strokeStyle = 'yellow';
ctx.lineWidth = 5; /* 设置线宽,单位为px */
ctx.strokeRect(100,100,200,100);### 绘制路径
## 绘制矩形
ctx.fillStyle = 'yellow';
ctx.beginPath();
ctx.moveTo(50,50);
ctx.lineTo(250,50);
ctx.lineTo(250,150);
ctx.lineTo(50,150);
ctx.fill();
## 绘制三角形
ctx.fillStyle = 'yellow';
ctx.beginPath();
ctx.moveTo(500,50);
ctx.lineTo(300,300);
ctx.lineTo(700,300);
ctx.fill();
## 绘制圆
ctx.fillStyle = 'yellow';
ctx.beginPath();
ctx.arc(300,300,200,0,2*Math.PI,false)
ctx.fill();
## 绘制部分圆
ctx.fillStyle = 'yellow';
ctx.beginPath();
ctx.arc(300,300,200,0,1/2*Math.PI,false)
ctx.lineTo(300,300) /* 注意这一步连接到圆心很重要 */
ctx.fill();### 绘制文本
## 方式1:
ctx.strokeStyle = 'yellow';
ctx.lineWidth = 2;
ctx.font = '40px arial';
ctx.strokeText('你好,Joden',100,100);
## 方式2:
ctx.fillStyle = 'blue';
ctx.font = '40px georgia';
ctx.fillText('Joden文本',500,100);### 绘制图片
var img = new Image();
img.src = 'p.jpg';
img.onload = ()=>{
ctx.drawImage(img,200,200);
}
# ctx.drawImage(Iamge,x,y)
# ctx.drawImage(Image,x,y,width,height)
# ctx.drawImage(Image,cut_x,cut_y,cut_width,cut_height,x,y,width,height)