导语
随着数据中心可视化系统的要求越来越高,2D、3D效果都要求几乎逼真;3D地板,相较于2D,实为更易,只需引擎(如:twaver.js、three.js等),外加一张地板图片,便可实现;本文重点介绍如何使用2D绘制地板、以及如何做出伪3D的地板效果;
先睹为快若有所思
看到如上效果,你也许会嘲笑鄙人;这样的效果,一张图片就解决,何以兴师动众,大动干戈;然,若您知道,房间地板的形状、材质参差不齐,如何一张图片能解决,你是否理解了我的所作所为,所思所想呢?
如你所想,这样给出地板材质和坐标信息,便很容易呈现形形状状的地板了,具体是如何实现的呢?
实验天地 Canvashtml5的Canvas标签,应该无需赘言, 若您对此不解,请移步 Canvas .
"给我一张Canvas,还你你个精彩世界";--世界著名学者Canvas
createPatternThe 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 .
imageCanvasImageSource to be used as image to repeat. It can either be a:
HTMLImageElement
HTMLVideoElement
HTMLCanvasElement
CanvasRenderingContext2D
ImageBitmap
Blob
repetitionDOMString 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></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上自己绘制地板样式,再用于填充,起步完美!
填充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> <canvas ></canvas> </body> </html>写到这,应该是对此技术应该非常熟练了,若想做出开篇的效果图,添加自己的创造,很容易便可实现;
参考资料 [1]. HTML5,不只是看上去很美(第二弹:打造最美3D机房) [2]. CanvasRenderingContext2D.createPattern [3]. Canvas