1. 创建一个canvas
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Canvas</title>
</head>
<body>
<canvas id="canvas" width="400" height="400"></canvas>
</body>
</html>
创建一个html,噢,我用的编辑器是PhpStorm,只需要写黑体的那一行,其它的是默认的模版。
保存这个文件,在Chrome中打开,后面的代码都可以在Chrome console中输入、运行(当然,也可以写到这个html中)。我习惯于把比较长的代码写在html中,或者新建一个js文件,在html中引用,然后,在console中调用写好的 js 函数。
2. 画一个实心矩形
var canvas =document.getElementById("canvas");
var ctx = canvas.getContext("2d");
ctx.fillRect(0, 0, 50, 50);
这几行代码看着非常熟悉哈,像Cocoa中的:
CGContextRef contextRef = UIGraphicsGetCurrentContext();
CGRect rect = CGRectMake(0, 0, 50, 50);
CGContextFillRect(context, rect);
多年前写windows程序,onPaint() 函数中好像也差不多。 都是拿到一个context,对context做一堆配置(颜色、线条、字体),然后,再执行一些绘图/写字函数。
3. 更改画笔的颜色
ctx.fillStyle = "Red";
ctx.fillRect(50,50,50,50);
颜色也可以这么写 "#f00" ,和CSS中一样。
4. 画一个空心矩形
ctx.strokeStyle = "Green";
ctx.lineWidth = 3;
ctx.strokeRect(10, 10, 100, 20);
stroke 在这里是 “笔划” 的意思,不是 “击打”。
5. 画线
ctx.beginPath();
ctx.moveTo(10, 10);
ctx.lineTo(60, 60);
ctx.moveTo(60, 10);
ctx.lineTo(10, 60);
ctx.stroke();
这是一个绿色的叉:
这个坐标还比较简单,容易想象。从小几何就学的不好,现在也很怕计算坐标,稍微复杂一点儿的图形就算不清楚坐标了。比如,下面这个:
6. 填充一个路径
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();7. 画弧线和圆
ctx.beginPath();
ctx.arc(50, 50, 20, 0, Math.PI / 2, false); // quarter circle
ctx.stroke();
ctx.beginPath();
ctx.arc(100, 50, 20, 0, Math.PI, false); // half circle
ctx.stroke();
ctx.beginPath();
ctx.arc(150, 50, 20, 0, Math.PI * 2, false); // full circle
ctx.stroke();

本文通过实例介绍如何使用HTML5的Canvas元素进行基本图形绘制,包括创建画布、绘制实心与空心矩形、画线、填充路径及画弧线和圆形。
1599

被折叠的 条评论
为什么被折叠?



