# canvas 2d 入门

canvas的坐标是右下坐标

canvas

绘制步骤

  1. 向HTML5页面添加canvas元素
  2. 通过js获取canvas对象,并创建contex对象
  3. 指定绘路径以及样式
  4. 开始绘制

html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    <canvas id="can" height="500" width="500"></canvas>
    <script src="./line.js"></script>
</body>
</html>
1
2
3
4
5
6
7
8
9
10
11
12
13
  • 定义好canvas2d画布

# 线

var canvas = document.getElementById('can');
var ctx = canvas.getContext('2d');
ctx.moveTo(100, 100);
ctx.lineTo(300, 300);
ctx.lineTo(100, 200);
ctx.stroke();
1
2
3
4
5
6

#

var canvas = document.getElementById('can');
var ctx = canvas.getContext('2d');
ctx.fillStyle = "#ff0";
ctx.beginPath();
ctx.arc(200, 200, 100, 0 * Math.PI, 2 * Math.PI);
ctx.closePath();
ctx.stroke(); // 描边
ctx.fill(); // 填充颜色
1
2
3
4
5
6
7
8
  • arc的参数: x坐标,y坐标,圆半径,起始角度,终点角度

# 渐变矩形

var canvas = document.getElementById('can');
var ctx = canvas.getContext('2d');
var grd = ctx.createLinearGradient(0, 0, 500, 500);
grd.addColorStop(0, 'red');
grd.addColorStop(0.5, 'blue');
grd.addColorStop(1, 'yellow');

ctx.fillStyle = grd;
ctx.fillRect(0, 0, 500, 500);
1
2
3
4
5
6
7
8
9
  • 定义渐变色 grd

#

var canvas = document.getElementById('can');
var ctx = canvas.getContext('2d');

ctx.font = '30px Arial';
ctx.fillText('yideng', 10, 50);
ctx.strokeText('xuetang', 10 ,200);
1
2
3
4
5
6

# 图片

var canvas = document.getElementById('can');
var ctx = canvas.getContext('2d');

var img = document.getElementById('images');
img.onload = function() {
    ctx.drawImage(img, 10, 10);
}
1
2
3
4
5
6
7