隨着數據中心可視化系統的要求愈來愈高,2D、3D效果都要求幾乎逼真;3D地板,相較於2D,實爲更易,只需引擎(如:twaver.js、three.js等),外加一張地板圖片,即可實現;本文重點介紹如何使用2D繪製地板、以及如何作出僞3D的地板效果;javascript
看到如上效果,你也許會嘲笑鄙人;這樣的效果,一張圖片就解決,何以興師動衆,大動干戈;然,若您知道,房間地板的形狀、材質良莠不齊,如何一張圖片能解決,你是否理解了個人所做所爲,所思所想呢?html
如你所想,這樣給出地板材質和座標信息,便很容易呈現形形狀狀的地板了,具體是如何實現的呢?java
HTML5的Canvas標籤,應該無需贅言, 若您對此不解,請移步Canvas.canvas
"給我一張Canvas,還你你個精彩世界";--世界著名學者Canvassegmentfault
The CanvasRenderingContext2D
.createPattern() method of the Canvas 2D API creates a pattern using the specified image (a CanvasImageSource ). It repeats the source in the directions specified by the repetition argument. This method returns a CanvasPattern .dom
imageide
CanvasImageSource to be used as image to repeat. It can either be a:spa
HTMLImageElementrest
HTMLVideoElementcode
HTMLCanvasElement
CanvasRenderingContext2D
ImageBitmap
Blob
repetition
DOMString indicating how to repeat the image. Possible values are:
"repeat" (both directions),
"repeat-x" (horizontal only),
"repeat-y" (vertical only), or
"no-repeat" (neither).
If repetition is an empty string ('') or null (but not undefined), repetition will be "repeat".
Example
<canvas id="canvas"></canvas> </pre> <pre> var canvas = document.getElementById('canvas'); var ctx = canvas.getContext('2d'); var img = new Image(); img.src = 'https://mdn.mozillademos.org/files/222/Canvas_createpattern.png'; img.onload = function() { var pattern = ctx.createPattern(img, 'repeat'); ctx.fillStyle = pattern; ctx.fillRect(0, 0, 400, 400); };
是否是很是的簡單,正如API所言,能夠支持圖片、Canvas、Vedio、Blob等等,所以,咱們能夠在Canvas上本身繪製地板樣式,再用於填充,起步完美!
<!DOCTYPE html> <html> <head> <title></title> <script type="text/javascript"> function init() { var canvas = document.getElementById("bg"); var ctx = canvas.getContext("2d"); var tile = document.createElement('canvas'); tile.width = 50; tile.height = 50; var tileCtx = tile.getContext("2d"); draw(tileCtx); var objPattern = ctx.createPattern(tile, "repeat"); ctx.rotate(-(Math.PI / 180) * 25); ctx.fillStyle = objPattern; ctx.fillRect(50, 300,700,400); } function draw(tileCtx) { var translator = new Translator3D({x:0,y:0,width:50,height:50}); tileCtx.save(); tileCtx.beginPath(); tileCtx.strokeStyle = 'rgba(100,100,0,1)'; var point = {x:0,y:25}; // point = translator.translate(point.x,point.y); tileCtx.moveTo(point.x, point.y); var point = {x:50,y:25}; // point = translator.translate(point.x,point.y); tileCtx.lineTo(point.x, point.y); var point = {x:25,y:0}; // point = translator.translate(point.x,point.y); tileCtx.moveTo(point.x, point.y); var point = {x:25,y:50}; // point = translator.translate(point.x,point.y); tileCtx.lineTo(point.x, point.y); tileCtx.stroke(); tileCtx.restore(); } </script> </head> <body onload="init();"> <canvas id="bg" width="1000" height="500" ></canvas> </body> </html>
寫到這,應該是對此技術應該很是熟練了,若想作出開篇的效果圖,添加本身的創造,很容易即可實現;
[1].HTML5,不僅是看上去很美(第二彈:打造最美3D機房)
[2].CanvasRenderingContext2D.createPattern
[3].Canvas