为了在canvas上绘製,你必须先得到一个画布上下文对象的引用,用本方法即可完成这一操作,格式如下:
context = canvas . getContext(contextId)
基本介绍
- 中文名:canvas 2D API
- 对应:二维Canvas
- 所属:Web页面
- 方法:getContext()方法
摘要
本规範定义了二维Canvas(画布)的绘画API,使用这些API使得可以在Web页面上进行立即模式的二维图形绘製。
1 Canvas接口元素定义DOM接口:
interfaceCanvasElement: Element{ attribute unsigned long width; attribute unsigned long height; Object getContext(in DOMString contextId); DOMString toDataURL(optional in DOMString type, in any... args); }; |
这里width和height必须是非负值,并且无论什幺时候重新设定了width或height的值,画布中任何已绘对象都将被清除,如下所示的JS代码中,仅仅最后一个矩形被绘製:
// canvas is a reference to a <canvas> element varcontext = canvas.getContext('2d'); context.fillRect(0,0,50,50); canvas.setAttribute('width', '300'); // clears the canvas context.fillRect(0,100,50,50); canvas.width = canvas.width; // clears the canvas context.fillRect(100,0,50,50); // only this square remains |
1.1 getContext()方法
为了在canvas上绘製,你必须先得到一个画布上下文对象的引用,用本方法即可完成这一操作,格式如下:
context = canvas . getContext(contextId)
方法返回一个指定contextId的上下文对象,如果指定的id不被支持,则返回null,当前唯一被强制必须支持的是“2d”,也许在将来会有“3d”,注意,指定的id是大小写敏感的。
1.2 toDataURL()方法
此函式,返回一张使用canvas绘製的图片,返回值符合data:URL格式,格式如下:
url = canvas . toDataURL( [ type, ... ])
规範规定,在未指定返回图片类型时,返回的图片格式必须为PNG格式,如果canvas没有任何像素,则返回值为:“data:,”,这是最短的data:URL,在text/plain资源中表现为空字元串。type的可以在image/png,image/jpeg,image/svg+xml等 MIME类型中选择。如果是image/jpeg,可以有第二个参数,如果第二个参数的值在0-1之间,则表示JPEG的质量等级,否则使用浏览器内置默认质量等级。
下面的代码可以从ID为codeex的canvas中取得绘製内容,并作为DataURL传递给img元素,并显示。
varcanvas = document.getElementById('codeex'); varurl = canvas.toDataURL(); //id为myimg的图片元素 myimg.src = url; |
1 二维绘图上下文 当使用一个canvas元素的getContext(“2d”)方法时,返回的是CanvasRenderingContext2D对象,其内部表现为笛卡尔平面坐标,并且左上角坐标为(0,0),在本平面中往右则x坐标增加和往下方y坐标增加。每一个canvas元素仅有一个上下文对象。其接口如下:
interfaceCanvasRenderingContext2D{ // back-reference to the canvas readonly attribute HTMLCanvasElement canvas; // state void restore(); // pop state stack and restore state void save(); // push state on state stack // transformations (default transform is the identity matrix) void rotate(in float angle); void scale(in float x, in float y); void setTransform(in float m11, in float m12, in float m21, in float m22, in float dx, in float dy); void transform(in float m11, in float m12, in float m21, in float m22, in float dx, in float dy); void translate(in float x, in float y); // compositing attribute float globalAlpha; // (default 1.0) attribute DOMString globalCompositeOperation; // (default source-over) // colors and styles attribute any fillStyle; // (default black) attribute any strokeStyle; // (default black) CanvasGradient createLinearGradient(in float x0, in float y0, in float x1, in float y1); CanvasGradient createRadialGradient(in float x0, in float y0, in float r0, in float x1, in float y1, in float r1); CanvasPattern createPattern(in HTMLImageElement image, in DOMString repetition); CanvasPattern createPattern(in HTMLCanvasElement image, in DOMString repetition); CanvasPattern createPattern(in HTMLVideoElement image, in DOMString repetition); // line styles attribute DOMString lineCap; // "butt", "round", "square" (default "butt") attribute DOMString lineJoin; // "miter", "round", "bevel" (default "miter") attribute float lineWidth; // (default 1) attribute float miterLimit; // (default 10) // shadows attribute float shadowBlur; // (default 0) attribute DOMString shadowColor; // (default transparent black) attribute float shadowOffsetX; // (default 0) attribute float shadowOffsetY; // (default 0) // rects void clearRect(in float x, in float y, in float w, in float h); void fillRect(in float x, in float y, in float w, in float h); void strokeRect(in float x, in float y, in float w, in float h); // Complex shapes (paths) API void arc(in float x, in float y, in float radius, in float startAngle, in float endAngle, in boolean anticlockwise); void arcTo(in float x1, in float y1, in float x2, in float y2, in float radius); void beginPath(); void bezierCurveTo(in float cp1x, in float cp1y, in float cp2x, in float cp2y, in float x, in float y); void clip(); void closePath(); void fill(); void lineTo(in float x, in float y); void moveTo(in float x, in float y); void quadraticCurveTo(in float cpx, in float cpy, in float x, in float y); void rect(in float x, in float y, in float w, in float h); void stroke(); boolean isPointInPath(in float x, in float y); // text attribute DOMString font; // (default 10px sans-serif) attribute DOMString textAlign; // "start", "end", "left", "right", "center" (default: "start") attribute DOMString textBaseline; // "top", "hanging", "middle", "alphabetic", "ideographic", "bottom" (default: "alphabetic") void fillText(in DOMString text, in float x, in float y, optional in float maxWidth); TextMetrics measureText(in DOMString text); void strokeText(in DOMString text, in float x, in float y, optional in float maxWidth); // drawing images void drawImage(in HTMLImageElement image, in float dx, in float dy, optional in float dw, in float dh); void drawImage(in HTMLImageElement image, in float sx, in float sy, in float sw, in float sh, in float dx, in float dy, in float dw, in float dh); void drawImage(in HTMLCanvasElement image, in float dx, in float dy, optional in float dw, in float dh); void drawImage(in HTMLCanvasElement image, in float sx, in float sy, in float sw, in float sh, in float dx, in float dy, in float dw, in float dh); void drawImage(in HTMLVideoElement image, in float dx, in float dy, optional in float dw, in float dh); void drawImage(in HTMLVideoElement image, in float sx, in float sy, in float sw, in float sh, in float dx, in float dy, in float dw, in float dh); // pixel manipulation ImageData createImageData(in float sw, in float sh); ImageData createImageData(in ImageData imagedata); ImageData getImageData(in float sx, in float sy, in float sw, in float sh); void putImageData(in ImageData imagedata, in float dx, in float dy, optional in float dirtyX, in float dirtyY, in float dirtyWidth, in float dirtyHeight); }; interfaceCanvasGradient{ // opaque object void addColorStop(in float offset, in DOMString color); }; interfaceCanvasPattern{ // opaque object }; interfaceTextMetrics{ readonly attribute float width; }; interfaceImageData{ readonly attribute CanvasPixelArray data; readonly attribute unsigned long height; readonly attribute unsigned long width; }; interfaceCanvasPixelArray{ readonly attribute unsigned long length; getter octet(in unsigned long index); setter void(in unsigned long index, in octet value); }; |
1.1 canvas的状态
每个上下文都包含一个绘图状态的堆,绘图状态包含下列内容:
² 当前的transformation matrix.
² 当前的clipping region
² 当前的属性值:fillStyle, font, globalAlpha,
globalCompositeOperation, lineCap, lineJoin,
lineWidth, miterLimit, shadowBlur, shadowColor,
shadowOffsetX, shadowOffsetY, strokeStyle, textAlign,
textBaseline
注:当前path和当前bitmap不是绘图状态的一部分,当前path是持久存在的,仅能被beginPath()复位,当前bitmap是canvas的属性,而非绘图上下文。
context. restore() //弹出堆最上面保存的绘图状态
context. save() //在绘图状态堆上保存当前绘图状态
绘图状态可以看作当前画面套用的所有样式和变形的一个快照。而状态的套用则可以避免绘图代码的过度膨胀。
1.2 转换(Transformations)
当建立形状和路径时,转换矩阵被套用到其坐标上。转换的执行顺序是严格按顺序的(注:原文是反向,经试验应该是按调用顺序的)。
在做转换/变形之前先保存状态是一个良好的习惯。大多数情况下,调用 restore 方法比手动恢复原先的状态要简单得多。又,如果你是在一个循环中做位移但没有保存和恢复 canvas 的状态,很可能到最后会发现怎幺有些东西不见了,那是因为它很可能已经超出 canvas 範围以外了。
context. rotate(angle) //按给定的弧度旋转,按顺时针旋转
rotate方法旋转的中心始终是canvas的原点,如果要改变它,需要使用translate方法。
context.translate(75,75); for (var i=1;i<6;i++){ context.save(); context.fillStyle = 'rgb('+(51*i)+','+(255-51*i)+',255)'; for (var j=0;j<i*6;j++){ context.rotate(Math.PI*2/(i*6)); context.beginPath(); context.arc(0,i*12.5,5,0,Math.PI*2,true); context.fill(); } context.restore(); } |
context. scale(x, y) //按给定的缩放倍率缩放,1.0,为不变
参数比1.0小表示缩小,否则表示放大。默认情况下,canvas 的 1 单位就是 1 个像素。举例说,如果我们设定缩放因子是 0.5,1 个单位就变成对应 0.5 个像素,这样绘製出来的形状就会是原先的一半。同理,设定为 2.0 时,1 个单位就对应变成了 2 像素,绘製的结果就是图形放大了 2 倍。
context. scale(x, y) //按给定的缩放倍率缩放,1.0,为不变
参数比1.0小表示缩小,否则表示放大。默认情况下,canvas 的 1 单位就是 1 个像素。举例说,如果我们设定缩放因子是 0.5,1 个单位就变成对应 0.5 个像素,这样绘製出来的形状就会是原先的一半。同理,设定为 2.0 时,1 个单位就对应变成了 2 像素,绘製的结果就是图形放大了 2 倍。
context. setTransform(m11, m12, m21, m22, dx, dy) //重设当前的转换到
context. transform(m11, m12, m21, m22, dx, dy) //矩阵变换,结果等于当前的变形矩阵乘上
m11 | m21 | dx |
m12 | m22 | dy |
0 | 0 | 1 |
后的结果
context. translate(x, y) //可以理解为偏移,向x,y方向偏移指定的量,其用来移动Canvas的原点到一个指定的值
. setTransform(m11, m12, m21, m22, dx, dy) //重设当前的转换到
context. transform(m11, m12, m21, m22, dx, dy) //矩阵变换,结果等于当前的变形矩阵乘上
m11 | m21 | dx |
m12 | m22 | dy |
0 | 0 | 1 |
后的结果
context. translate(x, y) //可以理解为偏移,向x,y方向偏移指定的量,其用来移动Canvas的原点到一个指定的值
综合实例
下面将是一个综合实例的JavaScript脚本:
1 context.fillStyle = '#00f';
2 context.strokeStyle = '#f00';
3 context.lineWidth = 4;
4 context.fillRect (0, 0, 150, 50);
5 context.strokeRect(0, 60, 150, 50);
6 context.clearRect (30, 25, 90, 60);
7 context.strokeRect(30, 25, 90, 60);
可以把上面代码放置在文档head部分中,或者放在外部JavaScript档案中。