https://github.com/caleb531/jcanvas
HTML5 可以直接在你的網頁中使用 <canvas> 元素及其相關的 JavaScript API繪制的圖形。
在這篇文章中,我將向你介紹 jCanvas,一個基於 jQuery的免費且開源的 HTML5的Canvas API。
如果你使用 jQuery 進行開發,jCanvas能夠使用 jQuery更簡單,更快速的完成一些非常炫酷的 canvas畫布及交互效果。
什么是 jCanvas ?
jCanvas 官網是這樣解釋的:
“jCanvas is a JavaScript library, written using jQuery and for jQuery, that wraps around the HTML5 canvas API, adding new features and capabilities, many of which are customizable. Capabilities include layers, events, drag-and-drop, animation, and much more.
The result is a flexible API wrapped up in a sugary, jQuery-esque syntax that brings power and ease to the HTML5 canvas. ”
jCanvas 能讓你做的一切事情,你都可以用原生的Canvas API來實現,甚至可以做更多的事情。如果你願意的話,你也可以將原生的Canvas API方法和 jCanvas一起使用。draw()方法就可以這樣使用。此外,你還可以非常輕松的用自己的方法結合 extend()函數來擴展jCanvas的功能。
添加jCanvas 到你的項目中
將jCanavs添加在你的項目中,從官方網站或GitHub的頁面上下載腳本,然后將腳本文件放在你的項目文件夾中。正如前面說的,jCanvas需要依賴 jQuery才能正常工作,所以還要確保引入了 jQuery文件。
項目的腳本文件將是這個樣子:
<script src="js/jquery.min.js></script> <script src="js/jcanvas.min.js></script> <script src="js/script.js></script>
最后,引入你自己的JavaScript 代碼文件。現在,讓我們開始jCanvas之旅吧。
設置 HTML文檔
我們通過為 HTMl5文檔添加一個<canvas>標簽,來開始我們的示例。
<canvas id="myCanvas" width="600" height="300"> <p>This is fallback content for users of assistive technologies or of browsers that don't have full support for the Canvas API.</p> </canvas>
以下是關於上面的代碼片段的幾點說明。
-
默認情況下,<canvas>的尺寸300px x 150px,你可以在width 和 height 屬性里修改默認的大小。
-
id屬性不是必須添加的,但是確是 JavaScript訪問該元素的最簡單的方法。
-
在<canvas>元素中的內容只是位圖,這使得它無法被使用輔助技術的用戶訪問。另外,對不支持 Canvas API的瀏覽器,將不能夠訪問其內容或者任何方式的交互。因此,該技術旨在讓<canvas>更容易被支持。
如果你想使用原生的Canvas API,你的 JavaScript 代碼將會這樣的:
var canvas = document.getElementById('myCanvas'), context = canvas.getContext('2d');
上述代碼中的context變量存儲了Canvas對象的一個2D上下文屬性。正是這種特性,使得你可以訪問 HTML5的 Canvas API提供的所有其他屬性和方法。
如果你想了解的更多,你可以戳這里HTML5 Canvas 簡介。
jCanvas的方法和屬性已經包含了2D上下文的引用,因此你可以直接的跳到繪制圖片。
用jCanvas繪制一些圖形
大多數的 jCanvas方法,接受鍵值對的形式,因此你可以根據你的需要,或你喜歡的順序去使用它們。
讓我們從繪制一個矩形開始吧。
矩形
下面是你怎樣用 jCanvas對象的 drawRect() 方法繪制出一個矩形的方法。
// Store the canvas object into a variable var $myCanvas = $('#myCanvas'); // rectangle shape $myCanvas.drawRect({ fillStyle: 'steelblue', strokeStyle: 'blue', strokeWidth: 4, x: 150, y: 100, fromCenter: false, width: 200, height: 100 });
上面的代碼片段表示,存儲 Canvas對象到一個名為$myCanvas的變量中。里面的drawRect()方法的屬性都是比較簡單的,但是我們在這里簡單的闡述一下:
-
fillStyle 設置矩形的背景色;
-
strokeStyle 設置它的邊框顏色;
-
strokeWidth 設置矩形的邊框寬度;
-
x 和 y設置對應矩形的坐標的水平和垂直的畫布內測的位置。頂點的0值的分別為 x和y,也就是說,(0,0),對應於畫布的左上角。x坐標向右增大,y坐標朝向畫布的底部增加。默認情況下,jCanvas會以矩形的中心點作為x和y坐標的值;
-
要想改變這一點,以便x和y對應矩形的左上角,可以將fromCenter屬性的值設置為 false;
-
最后,通過寬度和高度屬性設置矩形的尺寸。
下面是矩形的示例代碼:
HTML:
<h2>jCanvas example: Rectangle</h2> <canvas id="myCanvas" width="600" height="300"> <p>This is fallback content for users of assistive technologies or of browsers that don't have full support for the Canvas API.</p> </canvas>
CSS:
body { text-align: center; } canvas { margin: auto; display: block; }
JS:
// Store the canvas object into a variable var $myCanvas = $('#myCanvas'); // rectangle shape $myCanvas.drawRect({ fillStyle: 'steelblue', strokeStyle: 'blue', strokeWidth: 4, x: 190, y: 50, fromCenter: false, width: 200, height: 100 });
Result:
jCanvas example: Rectangle
圓弧和圓
弧是一個圓的邊緣部分。對於jCanvas來說,畫一個圓弧僅僅是在 drawArc() 方法里設置幾個所需的屬性:
$myCanvas.drawArc({ strokeStyle: 'steelblue', strokeStyle: 'blue', strokeWidth: 4, x: 300, y: 100, radius: 50, // start and end angles in degrees start: 0, end: 200 });
繪制弧形,需要設置半徑屬性的值,以及開始的角度和結束的角度。如果你希望弧形是逆時針方向的話,需要添加一個ccw屬性,並將其屬性值設置為true。
下面是上述代碼塊演示:
HTML:
<h2>jCanvas example: Arc</h2> <canvas id="myCanvas" width="600" height="300"> <p>This is fallback content for users of assistive technologies or of browsers that don't have full support for the Canvas API.</p> </canvas>
CSS:
body { text-align: center; } canvas { margin: auto; display: block; }
JS:
// Store the canvas object into a variable var $myCanvas = $('#myCanvas'); $myCanvas.drawArc({ strokeStyle: 'steelblue', strokeStyle: 'blue', strokeWidth: 4, x: 300, y: 100, radius: 50, // start and end angles in degrees start: 0, end: 200 });
Result:
jCanvas example: Arc
繪制一個圓形:
舉例來說,下面是如何只使用圓弧形狀來繪制出一個簡單的笑臉圖形:
$myCanvas.drawArc({ // draw the face fillStyle: 'yellow', strokeStyle: '#333', strokeWidth: 4, x: 300, y: 100, radius: 80 }).drawArc({ // draw the left eye fillStyle: '#333', strokeStyle: '#333', x: 250, y: 70, radius: 5 }).drawArc({ // draw the right eye fillStyle: '#333', strokeStyle: '#333', x: 350, y: 70, radius: 5 }).drawArc({ // draw the nose strokeStyle: '#333', strokeWidth: 4, ccw: true, x: 300, y: 100, radius: 30, start: 0, end: 200 }).drawArc({ // draw the smile strokeStyle: '#333', strokeWidth: 4, x: 300, y: 135, radius: 30, start: 90, end: 280 });
請記住,jCanvas是基於jQuery的,因此,你可以像jQuery的鏈式操作一樣,在jCanvas中也可以使用鏈式操作。
下面是以上代碼在瀏覽器中的效果:
HTML:
<h2>jCanvas example: Smiling Face</h2> <canvas id="myCanvas" width="600" height="300"> <p>This is fallback content for users of assistive technologies or of browsers that don't have full support for the Canvas API.</p> </canvas>
CSS:
body { text-align: center; } canvas { margin: auto; display: block; }
JS:
// Store the canvas object into a variable var $myCanvas = $('#myCanvas'); $myCanvas.drawArc({ // draw the face fillStyle: 'yellow', strokeStyle: '#333', strokeWidth: 4, x: 300, y: 100, radius: 80 }).drawArc({ // draw the left eye fillStyle: '#333', strokeStyle: '#333', x: 250, y: 70, radius: 5 }).drawArc({ // draw the right eye fillStyle: '#333', strokeStyle: '#333', x: 350, y: 70, radius: 5 }).drawArc({ // draw the nose strokeStyle: '#333', strokeWidth: 4, ccw: true, x: 300, y: 100, radius: 30, start: 0, end: 200 }).drawArc({ // draw the smile strokeStyle: '#333', strokeWidth: 4, x: 300, y: 135, radius: 30, start: 90, end: 280 });
Result:
jCanvas example: Smiling Face
繪制線條和路徑
你可以用drawLine()方法快速的繪制直線,或者定義一系列的線條的連接點。
$myCanvas.drawLine({ strokeStyle: 'steelblue', strokeWidth: 10, rounded: true, closed: true, x1: 100, y1: 28, x2: 50, y2: 200, x3: 300, y3: 200, x4: 200, y4: 109 });
上面代碼設置了 rounded和closed屬性的值為true,從而所繪制的線和角都是閉合的。
HTML:
<h2>jCanvas example: Connected lines</h2> <canvas id="myCanvas" width="600" height="300"> <p>This is fallback content for users of assistive technologies or of browsers that don't have full support for the Canvas API.</p> </canvas>
CSS:
body { text-align: center; } canvas { margin: auto; display: block; }
JS:
// Store the canvas object into a variable var $myCanvas = $('#myCanvas'); $myCanvas.drawLine({ strokeStyle: 'steelblue', strokeWidth: 10, rounded: true, closed: true, x1: 100, y1: 28, x2: 50, y2: 200, x3: 300, y3: 200, x4: 200, y4: 109 });
Result:
jCanvas example: Connected lines
還可以使用drawPath()方法繪制路徑。
該drawPath()方法設置 x 和 y值,你還需要制定你要繪制的路徑的類型,例如直線,圓弧等。
下面教你如何使用 drawPath()方法和drawarrows()方法畫出一對水平和垂直方向的箭頭,后者是一個非常好用的jCanvas方法,能夠使你快速的在畫布上繪制一個箭頭形狀:
$myCanvas.drawPath({ strokeStyle: '#000', strokeWidth: 4, x: 10, y: 10, p1: { type: 'line', x1: 100, y1: 100, x2: 200, y2: 100 }, p2: { type: 'line', rounded: true, endArrow: true, arrowRadius: 25, arrowAngle: 90, x1: 200, y1: 100, x2: 290, y2: 100 }, p3: { type: 'line', rounded: true, endArrow: true, arrowRadius: 25, arrowAngle: 90, x1: 100, y1: 100, x2: 100, y2: 250 } });
結果展示:
HTML:
<h2>jCanvas example: Connected Arrows</h2> <canvas id="myCanvas" width="600" height="300"> <p>This is fallback content for users of assistive technologies or of browsers that don't have full support for the Canvas API.</p> </canvas>
CSS:
body { text-align: center; } canvas { margin: auto; display: block; }
JS:
// Store the canvas object into a variable var $myCanvas = $('#myCanvas'); $myCanvas.drawPath({ strokeStyle: '#000', strokeWidth: 4, x: 10, y: 10, p1: { type: 'line', x1: 100, y1: 100, x2: 200, y2: 100 }, p2: { type: 'line', rounded: true, endArrow: true, arrowRadius: 25, arrowAngle: 90, x1: 200, y1: 100, x2: 290, y2: 100 }, p3: { type: 'line', rounded: true, endArrow: true, arrowRadius: 25, arrowAngle: 90, x1: 100, y1: 100, x2: 100, y2: 250 } });
Result:
jCanvas example: Connected Arrows
繪制文本
你可以使用drawText()方法快速的繪制出你需要的文字,這個方法的主要的功能:
-
text:將此屬性設置為你想要顯示在畫布上的文字內容:例如:‘Hello World’
-
fontsize:此屬性的值決定了在畫布上的文字的大小。你可以為這個屬性設置為一個數字,jCanvas默認為像素。另外,你也可以使用pt,但是在這種情況下,你需要用引號將屬性值包括起來
-
fontFamily:允許你指定您的文字圖像的字體:'Verdana, sans-serif'。
這里的示例代碼:
$myCanvas.drawText({ text: 'Canvas is fun', fontFamily: 'cursive', fontSize: 40, x: 290, y: 150, fillStyle: 'lightblue', strokeStyle: 'blue', strokeWidth: 1 });
在瀏覽器中將是這樣的效果:
HTML:
<h2>jCanvas example: Drawing text</h2> <canvas id="myCanvas" width="600" height="300"> <p>This is fallback content for users of assistive technologies or of browsers that don't have full support for the Canvas API.</p> </canvas>
CSS:
body { text-align: center; } canvas { margin: auto; display: block; }
JS:
// Store the canvas object into a variable var $myCanvas = $('#myCanvas'); $myCanvas.drawText({ text: 'jCanvas is fun', fontFamily: 'cursive', fontSize: 40, x: 290, y: 150, fillStyle: 'lightblue', strokeStyle: 'blue', strokeWidth: 1 });
Result:
jCanvas example: Drawing text
繪制圖片
你可以使用drawImage()方法來導入和處理圖片。下面是一個例子:
$myCanvas.drawImage({ source: 'imgs/cat.jpg', x: 250, y: 100, fromCenter: false, shadowColor: '#222', shadowBlur: 3, rotate: 40 });
這是上面代碼的呈現方式:
HTML:
<h2>jCanvas example: Importing and manipulating an image</h2> <canvas id="myCanvas" width="600" height="300"> <p>This is fallback content for users of assistive technologies or of browsers that don't have full support for the Canvas API.</p> </canvas>
CSS:
body { text-align: center; } canvas { margin: auto; display: block; }
JS:
// Store the canvas object into a variable var $myCanvas = $('#myCanvas'); $myCanvas.drawImage({ source: 'https://s3-us-west-2.amazonaws.com/s.cdpn.io/123941/cat.jpg', x: 250, y: 100, fromCenter: false, shadowColor: '#222', shadowBlur: 3, rotate: 40 });
Result:
jCanvas example: Importing and manipulating an image
你可以隨便的改變上面示例的代碼,戳這里:CodePen demo
Canvas層
如果你曾經使用過,如Photoshop或Gimp圖像編輯器類的應用程序,你可能會對圖層有所了解,使用圖層最爽的地方在於,你可以在畫布上控制每個圖像。
jCanvas提供了一個功能強大的API,基於你的畫布增加了靈活性。
這里介紹了如何使用jCanvas的層。
添加圖層
你只能在每一個層上繪制一個對象。在你的jCanvas項目中你有兩種添加圖層的方式:
-
使用 addLayer()方法,其次是drawLayers()方法
-
在任何的繪制方法里設置layer屬性的值為true
下面是如何運用第一種技術來繪制一個藍色矩形:
$myCanvas.addLayer({ type: 'rectangle', fillStyle: 'steelblue', fromCenter: false, name: 'blueRectangle', x: 50, y: 50, width: 400, height: 200 }).drawLayers();
HTML:
<h2>jCanvas example: Drawing a rectangle with addLayer()</h2> <canvas id="myCanvas" width="600" height="300"> <p>This is fallback content for users of assistive technologies or of browsers that don't have full support for the Canvas API.</p> </canvas>
CSS:
body { text-align: center; } canvas { margin: auto; display: block; }
JS:
// Store the canvas object into a variable var $myCanvas = $('#myCanvas'); $myCanvas.addLayer({ type: 'rectangle', fillStyle: 'steelblue', fromCenter: false, name: 'blueRectangle', x: 50, y: 50, width: 400, height: 200 }).drawLayers();
Result:
這里是你如何得到同樣矩形的第二種方法:
$myCanvas.drawRect({ fillStyle: 'steelblue', layer: true, name: 'blueRectangle', fromCenter: false, x: 50, y: 50, width: 400, height: 200 });
HTML:
<h2>jCanvas example: Using drawing method with layer set to "true"</h2> <canvas id="myCanvas" width="600" height="300"> <p>This is fallback content for users of assistive technologies or of browsers that don't have full support for the Canvas API.</p> </canvas>
CSS:
body { text-align: center; } canvas { margin: auto; display: block; }
JS:
// Store the canvas object into a variable var $myCanvas = $('#myCanvas'); $myCanvas.drawRect({ fillStyle: 'steelblue', layer: true, name: 'blueRectangle', fromCenter: false, x: 50, y: 50, width: 400, height: 200 });
Result:
正如你所看到的,上面的兩種方法,我們得到了相同的結果。
最重要的一點是在上面兩個代碼樣本中可以發現,上面的層你通過name設置的一個名稱。這使得他易於參照本層的代碼做出各種炫酷的東西,像改變其索引值,動畫,刪除等等。
讓我們看看如何能夠做到這一點。
動畫層
你可以使用jCanvas的 animateLayer()方法,快速的在你的基礎圖層上添加動畫,此方法接受以下參數:
-
該層的 index 或者 name
-
具有鍵值對的動畫對象
-
以毫秒為單位的動畫時長(duration)。這是個默認的參數,如果不設置,默認為400
-
動畫的運動方式(easing )。這也是一個可選的參數,如果不設置,則默認為搖擺
-
動畫完成之后的回調函數(callback),也是可選的。
讓我們來看一下animateLayer() 方法的效果,我們將在一個層上繪制一個半透明的橙色圓圈,然后設置動畫的位置,顏色以及透明度屬性:
// Draw circle $myCanvas.drawArc({ name: 'orangeCircle', layer: true, x: 50, y: 50, radius: 100, fillStyle: 'orange', opacity: 0.5 }); // Animate the circle layer $myCanvas.animateLayer('orangeCircle', { x: 150, y: 150, radius: 50, }, 1000, function(layer) { // Callback function $(this).animateLayer(layer, { fillStyle: 'darkred', x: 250, y: 100, opacity: 1 }, 'slow', 'ease-in-out'); });
看一下下面例子中的動畫:
HTML:
<h2>jCanvas example: Animating Layers</h2> <canvas id="myCanvas" width="600" height="300"> <p>This is fallback content for users of assistive technologies or of browsers that don't have full support for the Canvas API.</p> </canvas>
CSS:
body { text-align: center; } canvas { margin: auto; display: block; }
JS:
// Store the canvas object into a variable var $myCanvas = $('#myCanvas'); // Draw circle $myCanvas.drawArc({ name: 'orangeCircle', layer: true, x: 50, y: 50, radius: 100, fillStyle: 'orange', opacity: 0.5 }); // Animate the circle layer $myCanvas.animateLayer('orangeCircle', { x: 150, y: 150, radius: 50, }, 1000, function(layer) { // Callback function $(this).animateLayer(layer, { fillStyle: 'darkred', x: 250, y: 100, opacity: 1 }, 'slow', 'ease-in-out'); });
Result:
jCanvas example: Animating Layers
可拖動圖層
我想提醒你注意的是它還有一個很酷的功能,你可以在可拖動層里設置draggable屬性和layer 屬性的值為true,就可以將一個普通的jCanvas層變成可拖動的層了。
具體方法如下:
$myCanvas.drawRect({ layer: true, draggable: true, bringToFront: true, name: 'blueSquare', fillStyle: 'steelblue', x: 250, y: 150, width: 100, height: 100, rotate: 80, shadowX: -1, shadowY: 8, shadowBlur: 2, shadowColor: 'rgba(0, 0, 0, 0.8)' }) .drawRect({ layer: true, draggable: true, bringToFront: true, name: 'redSquare', fillStyle: 'red', x: 190, y: 100, width: 100, height: 100, rotate: 130, shadowX: -2, shadowY: 5, shadowBlur: 3, shadowColor: 'rgba(0, 0, 0, 0.5)' });
在上面的代碼段中,通過把屬性draggable設置為true,繪制出了兩個可拖動的矩形層。此外,請小心使用bringToFront屬性,以確保當你拖動層時,他會被自動拖到所有其他現有的圖層的前面。
最后,在上述代碼段中添加旋轉圖層的代碼並且設置一個盒子陰影,只是為了告訴你如何快速的在你的jCanvas圖紙上添加一些特效。
結果會是這樣的:
如果你想在在你拖動圖層之前,之間或者之后做一些事情的話,jCanvas 可以很容易的利用相關的回調函數來實現這一點:
-
dragstart:當你開始拖動圖層的時候的觸發器
-
drag:當你正在拖動圖層時發生
-
dragstop:當你停止拖動圖層時的觸發器
-
dragcancel:當你拖動的圖層到了畫布表面的邊界時發生
比方說,當用戶完成拖動層之后,你想在頁面上顯示一條消息,你可以通過添加一個回調函數dragstop來實現,就像這樣:
$myCanvas.drawRect({ layer: true, // Rest of the code as shown above... // Callback function dragstop: function(layer) { var layerName = layer.name; el.innerHTML = 'The ' + layerName + ' layer has been dropped.'; } }) .drawRect({ layer: true, // Rest of the code... // Callback function dragstop: function(layer) { var layerName = layer.name; el.innerHTML = 'The ' + layerName + ' layer has been dropped.'; } });
結論
在這篇文章中,我向你介紹了jCanvas,一個新的基於jQuery能與HTML5的 Canvas API一起使用的庫。我已經簡單的介紹了一些jCanvas的屬性和方法,能夠讓你快速的在畫布和是哪個繪制圖形,增加視覺效果,動畫和拖動圖層。
你可以訪問jCanvas文檔,這里有很多的詳細指導和示例。你要可以在 jCanvas網站的 sandbox上進行快速測試。