為了在canvas上繪製,你必須先得到一個畫布上下文對象的引用,用本方法即可完成這一操作,格式如下:
context = canvas . getContext(contextId)
基本介紹
- 中文名:canvas 2D API
- 對應:二維Canvas
- 所屬:Web頁面
- 方法:getContext()方法
摘要,1.1 getContext()方法,1.2 toDataURL()方法,1.1 canvas的狀態,1.2 轉換(Transformations),綜合實例,
摘要
本規範定義了二維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); }; |
// 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, ... ])
下面的代碼可以從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檔案中。