前端開(kāi)發(fā)的重要一環(huán)便是圖形繪制,但是Javascript自帶的繪圖功能有限,在高級(jí)繪圖功能上非常不足。為了彌補(bǔ)這一問(wèn)題,各種Javascript2D繪圖庫(kù)開(kāi)始出現(xiàn),例如EaselJS、Paper.js,本文將著重講解這些工具的使用和優(yōu)點(diǎn)。
Paper.js
Paper.js是一款輕量級(jí)的基于HTML5的矢量圖形Javascript庫(kù),擁有出色的畫(huà)布繪制和動(dòng)畫(huà)處理。下面我們來(lái)看一個(gè)簡(jiǎn)單的例子。HTML代碼如下:
<!-- 引入Paper.js --> <script src="https://cdnjs.cloudflare.com/ajax/libs/paper.js/0.12.2/paper-full.min.js"></script> <canvas id="myCanvas" resize="true"></canvas>
然后在Javascript代碼中我們可以使用Paper.js來(lái)進(jìn)行繪制工作:
<script> // 定義畫(huà)布和路徑 var canvas = document.getElementById('myCanvas'); paper.setup(canvas); var path = new paper.Path(); // 繪制路徑 path.strokeColor = 'black'; var start = new paper.Point(100, 100); path.moveTo(start); path.lineTo(start.add([ 200, -50 ])); // 渲染畫(huà)布 paper.view.draw(); </script>
EaselJS
EaselJS是一個(gè)面向HTML5 Canvas的Javascript庫(kù),它為開(kāi)發(fā)者提供了完善的繪圖基礎(chǔ)設(shè)施。
使用EaselJS來(lái)創(chuàng)建一個(gè)簡(jiǎn)單畫(huà)板的例子。HTML代碼如下:
<!-- 引入 EaselJS --> <script src="https://code.createjs.com/easeljs-0.8.2.min.js"></script> <canvas id="canvas" width="400" height="400"></canvas>
Javascript代碼如下:
<script> var canvas, stage, color = "black", size = 4, oldPt, oldMidPt, drawingCanvas, drawingArea; function init() { canvas = document.getElementById("canvas"); stage = new createjs.Stage(canvas); stage.autoClear = false; stage.enableDOMEvents(true); createjs.Touch.enable(stage); createjs.Ticker.framerate = 24; drawingCanvas = new createjs.Shape(); stage.addEventListener("stagemousedown", handleMouseDown); stage.addEventListener("stagemouseup", handleMouseUp); stage.addChild(drawingCanvas); stage.update(); } function handleMouseDown(event) { if (stage.contains(event.target)) { color = "#"+((1<<24)*Math.random()|0).toString(16); size = 4; oldPt = new createjs.Point(stage.mouseX, stage.mouseY); oldMidPt = oldPt; stage.addEventListener("stagemousemove", handleMouseMove); } } function handleMouseMove(event) { if (stage.contains(event.target)) { var midPt = new createjs.Point(oldPt.x + stage.mouseX>>1, oldPt.y+stage.mouseY>>1); drawingCanvas.graphics.setStrokeStyle(size, 'round', 'round') .beginStroke(color) .moveTo(midPt.x, midPt.y) .curveTo(oldPt.x, oldPt.y, oldMidPt.x, oldMidPt.y); oldPt.x = stage.mouseX; oldPt.y = stage.mouseY; oldMidPt.x = midPt.x; oldMidPt.y = midPt.y; stage.update(); } } function handleMouseUp(event) { if (stage.contains(event.target)) { stage.removeEventListener("stagemousemove", handleMouseMove); } } init(); </script>
以上代碼定義了一個(gè)畫(huà)板,用戶可以在畫(huà)板上以鼠標(biāo)建立各種顏色、粗細(xì)的線條。
結(jié)語(yǔ)
Javascript2D繪圖庫(kù)為前端開(kāi)發(fā)提供了更便捷和強(qiáng)大的圖形繪制方式,可以實(shí)現(xiàn)各種高級(jí)繪圖效果。本文介紹了兩款主流的Javascript2D繪圖庫(kù),使得前端開(kāi)發(fā)者們可以在更加簡(jiǎn)單的條件下實(shí)現(xiàn)復(fù)雜的圖形繪制和交互操作。