线
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<canvas id="can" width="600" height="600"></canvas>
</body>
</html>
<script>
var canvas = document.getElementById('can');
canvas.style.border = '1px solid red';
var ctx = canvas.getContext('2d');
ctx.moveTo(100,100); //移动到某个坐标,相当于用画笔点一下,然后开始画
ctx.lineTo(200,100); //画了一条线
ctx.stroke();//描边
</script>
三角形
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<canvas id="can" width="600" height="600"></canvas>
</body>
</html>
<script>
var canvas = document.getElementById('can');
canvas.style.border = '1px solid red';
var ctx = canvas.getContext('2d');
ctx.moveTo(100,100); //移动到某个坐标,相当于用画笔点一下,然后开始画
ctx.lineTo(200,100); //画了一条线
ctx.lineTo(100,200);
ctx.closePath(); // 闭合路径
ctx.strokeStyle = 'green';
ctx.stroke();//描边
ctx.fillStyle = 'yellow';
ctx.fill();//填充
</script>
互不干扰的线
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<canvas id="can" width="600" height="600"></canvas>
</body>
</html>
<script>
var canvas = document.getElementById('can');
canvas.style.border = '1px solid red';
var ctx = canvas.getContext('2d');
ctx.beginPath(); //规范化写法,绘制元素前必须beginPath()
ctx.moveTo(100,100); //移动到某个坐标,相当于用画笔点一下,然后开始画
ctx.lineTo(200,100); //画了一条线
ctx.strokeStyle = 'green';
ctx.lineWidth = 10;
ctx.stroke();//描边
ctx.beginPath();//重新开始画新元素,如果没有这句,都变成红色线了
ctx.moveTo(100,200);
ctx.lineTo(300,200);
ctx.strokeStyle = 'red';
ctx.stroke();//描边
</script>
矩形、圆
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<canvas id="can" width="600" height="600"></canvas>
</body>
</html>
<script>
var canvas = document.getElementById('can');
canvas.style.border = '1px solid red';
var ctx = canvas.getContext('2d');
ctx.beginPath();
ctx.rect(100,100,50,50); // 前两个参数是坐标,后两个参数是宽和高
ctx.strokeStyle = 'green';
ctx.lineWidth = 2;
ctx.stroke();//描边
ctx.beginPath();
ctx.arc(200,200,50,0, Math.PI*2);//xy坐标,半径,起始、结束角度(弧度)
ctx.fillStyle = 'red';
ctx.fill();//描边
</script>
文字
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<canvas id="can" width="600" height="600"></canvas>
</body>
</html>
<script>
var canvas = document.getElementById('can');
canvas.style.border = '1px solid red';
var ctx = canvas.getContext('2d');
ctx.beginPath();
// 设置字体
ctx.font = "18px bold 黑体";
// 设置颜色
ctx.fillStyle = "red";
// 设置水平对齐方式
ctx.textAlign = "center";
// 设置垂直对齐方式
ctx.textBaseline = "middle";
// 绘制文字(参数:要写的字,x坐标,y坐标)
ctx.fillText("你好", 100, 100);
</script>
网友评论