canvas 学习笔记(一)

canvas元素 翻译过来是 画布,帆布
最早在苹果浏览器中引进,逐渐普及成HTML5的 标准Element 这个元素的具体参见可以看
这里
通过canvas我们可以在浏览器中画出很多不规则或是规则的图形
如何画呢?
在HTML5的标准里看到DOM接口的描述

canvas元素只有2个属性,分别是heightwidth

toDataURL:
这个方法可以返回一个URL形式的在canvas 画布中的图片数据,这个图片数据是64位编码的。
第一个参数指定他的返回图片格式(e.g. PNG or JPEG)
默认情况下是 image/png 还可以是 image/jpeg, 第二个参数如果指定的话,则是生成图片的质量,值在(0-1)之间

getContext:
这个方法可以返回一个包含绘图API的对象,如果contextId不被支持则会返回空,目前常用的是’2d’内容 ,今后有可能会加入OpenGL ES 为基础的3D 内容。

要想在canvas上画东西,必须通过getContext这个方法获得对context对象的引用

var canvas = document.getElementById("canvas");
var ctx = canvas.getContext(contextId);

方形
当我们获得了context的引用我们就可以开始作画了

var canvas = document.getElementById("canvas");
var ctx = canvas.getContext('2d');
ctx.translate(10,10);
ctx.fillStyle = "#C00";
ctx.fillRect(0,0,100,100);//填充一个方形

fillRect(x,y,width,height) : Draws a filled rectangle //填充一个方形区域
strokeRect(x,y,width,height) : Draws a rectangular outline //画一个方形区域的轮廓
clearRect(x,y,width,height) : Clears the specified area and makes it fully transparent //清除一个方形区域

canvas 只支持方形,所有的其他形状都是有一条或是多条路径所创建组合的
就是用到是路径的api了

//path API
void beginPath();
void closePath();
void moveTo(in float x, in float y);
void lineTo(in float x, in float y);
void quadraticCurveTo(in float cpx, in float cpy, in float x, in float y);
void bezierCurveTo(in float cp1x, in float cp1y, in float cp2x, in float cp2y, in float x, in float y);
void arcTo(in float x1, in float y1, in float x2, in float y2, in float radius);
void rect(in float x, in float y, in float w, in float h);
void arc(in float x, in float y, in float radius, in float startAngle, in float endAngle, in boolean anticlockwise);
void fill();
void stroke();
void clip();
boolean isPointInPath(in float x, in float y);


让我们用路径来画一个圆

ctx.beginPath();
ctx.moveTo(50,50);
ctx.arc(50,50,40,0,Math.PI*2,true);
ctx.closePath();
ctx.fillStyle = "#C00";
ctx.fill();


二次贝塞尔曲线和三次贝塞尔曲线
需要注意的是二次贝塞尔曲线在1.5版本的 firefox 下会有bug 需要转成三次贝塞尔曲线作图

quadraticCurveTo(cp1x, cp1y, x, y) // BROKEN in Firefox 1.5
bezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y)

bezierCurveTo()这个方法是在画布上画一条 贝塞尔曲线 ,参数 cp1x,cp1y,cp2x,cp2y 的分别表示的是图中的红色的控制点的坐标, x,y 是曲线终点的坐标

关于贝塞尔曲线的知识点这里

用贝塞尔曲线作图

ctx.beginPath();
ctx.moveTo(50,50);
ctx.bezierCurveTo(50,0,100,0,100,50);
ctx.moveTo(100,50);
ctx.bezierCurveTo(100,100,150,100,150,50);
ctx.strokeStyle = "#C00";
ctx.stroke();

Posted in HTML5, javascript by qbaty at 三月 22nd, 2010.
Tags: , ,

Leave a Reply