DHTMLSprite
最近研究了下DHTMLsprite,用于绘画动画。尽管创建这玩意有更好更高效的方式,比如HTML5 canvas。但是如果要兼容不支持HTML5特性的游览器,DHTMLsprite是一个不错的选择。先说说原理,我们常常用CSS sprite来减少HTTP请求,但这样的方式,也可以用于动画,游戏的需求。我们知道,在web上控制一个角色,我们是在不停的生成可移动的角色,于是乎,我们可以改变backgroundPosition的值,来求算需要移动的像素值。
上个DEMO,可以研究研究。
///images图像文件路径///ImagesWidth图像文件的像素宽度///width sprite的像素宽度///height sprite的像素高度///$drawTarget sprite将要附加的父元素var DHTMLsprite = function (params) { var width = params.width, height = params.height, imageswidth = params.imageswidth, $element = params.$drawTarget.append('<div/>').find(':last'), elemStyle = $element[0].style, mathFloor = Math.floor; $element.css({ position: 'absolute', width: width, height: height, backgroundImage: 'url(' + params.images + ')' }); var that = { draw: function (x, y) { elemStyle.left = x + 'px'; elemStyle.top = y + 'px'; }, changeImage: function (index) { index *= width; var vOffset = -mathFloor(index / imageswidth) * height; var hOffset = -index % imageswidth; elemStyle.backgroundPosition = hOffset + 'px' + ' ' + vOffset + 'px'; }, show: function () { elemStyle.display = 'block'; }, hide: function () { elemStyle.display = 'none'; }, destroy: function () { $element.remove(); } }; return that;};//x 像素x的位置//y 像素y的位置//xDir x移动方向//yDir y移动方向//maxX 最大x位置//mayY 最大y位置var bouncySprite = function (params) { var x = params.x, y = params.y, xDir = params.xDir, yDir = params.yDir, maxX = params.maxX, mayY = params.mayY, animIndex = 0, that = DHTMLsprite(params); that.moveAndDraw = function () { x += xDir; y += yDir; animIndex += xDir > 0 ? 5 : -1; animIndex %= 5; animIndex += animIndex < 0 ? 5 : 0; if ((xDir < 0 && x < 0) || (xDir > 0 && x >= maxX)) { xDir = -xDir; } if ((yDir < 0 && y < 0) || (yDir > 0 && x >= mayY)) { yDir = -yDir; } that.changeImage(animIndex); that.draw(x, y); }; return that;};//numBouncy 需要初始化的bouncySprite个数//$drawTarget bouncySprite需要添加到的目标父元素var bouncyBoss = function (numBouncy, $drawTarget) { var bouncys = []; for (var i = 0; i < numBouncy; i++) { bouncys.push(bouncySprite({ images: 'nav_logo114.png', imageswidth: 256, width: 64, height: 64, $drawTarget: $drawTarget, x: Math.random() * ($drawTarget.width() - 64), y: Math.random() * ($drawTarget.height() - 64), xDir: Math.random() * 4 - 2, yDir: Math.random() * 4 - 2, maxX: $drawTarget.width() - 64, mayY: $drawTarget.height() - 64 })); } var moveAll = function () { var len = bouncys.length; for (var i = 0; i < len; i++) { bouncys[i].moveAndDraw(); } setTimeout(moveAll, 10); } moveAll();};
此段js保存为 sprite.js
<!DOCTYPE html><html #draw-target { width:100%; height:320px; background-color:#ccf; position:relative; } </style> <script type="text/javascript"> $(function () { bouncyBoss(2, $('#draw-target')); }); </script></head><body> <div id="draw-target"></div></body></html>
TAG: