1. canvas 基础 api
var canvas = document.getElementById('canvas');
// 设置canvas画布的宽度,其默认宽度为300
canvas.width = 1024;
// 设置canvas画布的高度,其默认高度为150
canvas.height = 768;
// 获取canvas的上下文环境,多数都是用2d,表示平面
var ctx = canvas.getContext('2d');
// 表示开始一段路径
ctx.beginPath();
// 移动到100, 200坐标点,canvas以左上角为原点,向右为x轴正方向,向下为y轴正方向
ctx.moveTo(100,200);
// 从(100,200)连线到(200, 300)
ctx.lineTo(200, 300);
// 又从(200, 300)连线到(300, 200)
ctx.lineTo(300, 200);
// 关闭当前路径,该方法最好在stroke方法之前调用,该方法可以不和beginPath连用
// 当该方法使用时,所画的的线会首尾会自动连接起来
ctx.closePath();
// 设置线的颜色
ctx.strokeStyle = 'red';
// 设置线宽
ctx.lineWidth = '5';
// 绘画
ctx.stroke();
// 图形的填充色
ctx.fillStyle = "blue";
// 进行填充
ctx.fill();
执行结果
2. 练习画七巧板
七巧板效果图
3. canvas 画圆
var canvas = document.getElementById('canvas');
canvas.width = 400;
canvas.height = 800;
var ctx = canvas.getContext('2d');
// 主要api
/**
* x: 圆心横坐标
* y: 圆心纵坐标
* radius: 圆的半径
* sAngle: 圆的起始角
* eAngle: 圆的结束角
* counterclockwise: 可选,规定逆时针还是顺时针 默认为false,顺时针
*
*/
ctx.arc(x, y, radius, sAngle, eAngle, counterclockwise )
圆的开始角与结束角
image.png
相关练习
var canvas = document.getElementById('canvas');
canvas.width = 400;
canvas.height = 800;
var ctx = canvas.getContext('2d');
var color = '#ff0000';
var fillColor = '#abcdef';
for(var i = 0; i < 10; i++){
ctx.beginPath();
ctx.arc(20+ i * 40, 30, 15, 0, (i + 1) * .2 * Math.PI);
ctx.strokeStyle = color;
ctx.closePath();
ctx.stroke()
}
for(var i = 0; i < 10; i++){
ctx.beginPath();
ctx.arc(20+ i * 40, 80, 15, 0, (i + 1) * .2 * Math.PI);
ctx.strokeStyle = color;
ctx.stroke()
}
for(var i = 0; i < 10; i++){
ctx.beginPath();
ctx.arc(20+ i * 40, 130, 15, 0, (i + 1) * .2 * Math.PI);
ctx.strokeStyle = color;
ctx.stroke();
ctx.fillStyle = fillColor;
ctx.fill();
}
for(var i = 0; i < 10; i++){
ctx.beginPath();
ctx.arc(20+ i * 40, 180, 15, 0, (i + 1) * .2 * Math.PI);
ctx.strokeStyle = color;
ctx.closePath();
ctx.stroke();
ctx.fillStyle = fillColor;
ctx.fill();
}
for(var i = 0; i < 10; i++){
ctx.beginPath();
ctx.arc(20+ i * 40, 230, 15, 0, (i + 1) * .2 * Math.PI, true);
ctx.strokeStyle = color;
ctx.closePath();
ctx.stroke()
}
运行结果截图
注意对比下
beginPath()
和closePath()
连用,不连用的情况;存在fill()
方法和不存在对圆的影响;顺时针
和逆时针
的影响