canvas学习笔记

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()方法和不存在对圆的影响;顺时针逆时针的影响

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 一、canvas简介 1.1 什么是canvas?(了解) 是HTML5提供的一种新标签 Canvas是一个矩形区...
    Looog阅读 3,974评论 3 40
  • 基本信息 默认为 inline ,默认大小为 width:300px;height:150px;,默认 黑色 默认...
    _月光临海阅读 453评论 0 1
  • 最基本的使用创建一个画布所有的操作都在画布的context上面canvas是基于状态而不是基于对象的,比如说颜色都...
    亲爱的孟良阅读 1,678评论 0 4
  • 参考 使用canvas来绘制图形 知识点 图形的基本元素是路径。路径是通过不同颜色和宽度的线段或曲线相连形成的不同...
    小人物的秘密花园阅读 474评论 0 0
  • canvas制造2d环境: var txt = cvs.grtContext(‘2d’); 绘制矩形: fillR...
    WeekOne阅读 349评论 0 0