(一)在画布绘制空心与实心矩形
<html>
<head>
<title>Canvas</title>
<meta http-equiv="content-type" content="text/html;charset=utf-8">
</head>
<body>
<canvas id="canvas" width="200" height="200"></canvas>
<script>
//选择id为canvas的元素
var canvas = document.getElementById("canvas");
//重canvas元素获取绘制环境
var ctx = canvas.getContext("2d");
//要使用不同的颜色,可以更改绘制环境的fillStyle属性
ctx.fillStyle = "Red";
//绘制实心正方形
ctx.fillRect(0,0,100,100);
//设置线条颜色
ctx.strokeStyle = "DeepPink";
//设置线条宽度
ctx.lineWidth = 4;
//绘制空心正方形
ctx.strokeRect(100,100,96,96);
</script>
</body>
</html>
<html>
<head>
<title>Canvas</title>
<meta http-equiv="content-type" content="text/html;charset=utf-8">
</head>
<body>
<canvas id="canvas" width="200" height="200"></canvas>
<script>
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
ctx.strokeStyle = "Turquoise";
ctx.lineWidth = 4;
//告诉canvas我们要开始绘制一条新的路径
ctx.beginPath();
ctx.moveTo(10,10);//起点
ctx.lineTo(60,60);//终点
ctx.moveTo(60,10);
ctx.lineTo(10,60);
ctx.stroke();//调用stroke方法,使线条出现在屏幕
</script>
</body>
</html>
(三)填充路径
<html>
<head>
<title>Canvas</title>
<meta http-equiv="content-type" content="text/html;charset=utf-8">
</head>
<body>
<canvas id="canvas" width="200" height="200"></canvas>
<script>
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
ctx.fillStyle = "Turquoise";
ctx.beginPath();
//连成一个封闭区域
ctx.moveTo(100,100);
ctx.lineTo(100,60);
ctx.lineTo(130,30);
ctx.lineTo(160,60);
ctx.lineTo(160,100);
ctx.lineTo(100,100);
ctx.fill();
</script>
</body>
</html>
(四)绘制圆
<html>
<head>
<title>Canvas</title>
<meta http-equiv="content-type" content="text/html;charset=utf-8">
</head>
<body>
<canvas id="canvas" width="200" height="200"></canvas>
<script>
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var circle = function(x,y,radius){
ctx.beginPath();
//(x,y)-圆心
//radius-半径
//0代表在x正半轴
//Math.PI*2代表旋转多少度
//flase表示顺时针方向转
ctx.arc(x,y,radius,0,Math.PI*2,false);
ctx.stroke();
};
ctx.lineWidth = 4;
ctx.strokeStyle = "Red";
circle(100,100,10);
ctx.strokeStyle = "Orange";
circle(100,100,20);
ctx.strokeStyle = "Yellow";
circle(100,100,30);
ctx.strokeStyle = "Green";
circle(100,100,40);
ctx.strokeStyle = "Blue";
circle(100,100,50);
ctx.strokeStyle = "Purple";
circle(100,100,60);
</script>
</body>
</html>