Files
CanvasLoader/docs/files/src_canvasloader.js.html
Robert Pataki bc1d7291c5 - Update docs,
- Update Grunt build task
- Remove obsolete variables
- Update jQuery plugin
2014-08-20 13:48:39 +01:00

719 lines
22 KiB
HTML

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>src/canvasloader.js - canvasloader</title>
<link rel="stylesheet" href="http://yui.yahooapis.com/3.9.1/build/cssgrids/cssgrids-min.css">
<link rel="stylesheet" href="../assets/vendor/prettify/prettify-min.css">
<link rel="stylesheet" href="../assets/css/main.css" id="site_styles">
<link rel="shortcut icon" type="image/png" href="../assets/favicon.png">
<script src="http://yui.yahooapis.com/combo?3.9.1/build/yui/yui-min.js"></script>
</head>
<body class="yui3-skin-sam">
<div id="doc">
<div id="hd" class="yui3-g header">
<div class="yui3-u-3-4">
<h1><img src="../assets/css/logo.png" title="canvasloader"></h1>
</div>
<div class="yui3-u-1-4 version">
<em>API Docs for: 0.9.1</em>
</div>
</div>
<div id="bd" class="yui3-g">
<div class="yui3-u-1-4">
<div id="docs-sidebar" class="sidebar apidocs">
<div id="api-list">
<h2 class="off-left">APIs</h2>
<div id="api-tabview" class="tabview">
<ul class="tabs">
<li><a href="#api-classes">Classes</a></li>
<li><a href="#api-modules">Modules</a></li>
</ul>
<div id="api-tabview-filter">
<input type="search" id="api-filter" placeholder="Type to filter APIs">
</div>
<div id="api-tabview-panel">
<ul id="api-classes" class="apis classes">
<li><a href="../classes/CanvasLoader.html">CanvasLoader</a></li>
</ul>
<ul id="api-modules" class="apis modules">
<li><a href="../modules/CanvasLoader.html">CanvasLoader</a></li>
</ul>
</div>
</div>
</div>
</div>
</div>
<div class="yui3-u-3-4">
<div id="api-options">
Show:
<label for="api-show-inherited">
<input type="checkbox" id="api-show-inherited" checked>
Inherited
</label>
<label for="api-show-protected">
<input type="checkbox" id="api-show-protected">
Protected
</label>
<label for="api-show-private">
<input type="checkbox" id="api-show-private">
Private
</label>
<label for="api-show-deprecated">
<input type="checkbox" id="api-show-deprecated">
Deprecated
</label>
</div>
<div class="apidocs">
<div id="docs-main">
<div class="content">
<h1 class="file-heading">File: src/canvasloader.js</h1>
<div class="file">
<pre class="code prettyprint linenums">
/*
* Copyright (c) 2014 Róbert Pataki
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the &quot;Software&quot;), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED &quot;AS IS&quot;, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* ----------------------------------------------------------------------------------------
*
* Check out my GitHub: http://github.com/robertpataki/
* Send me an email: robert@robertpataki.com
* Follow me on Twitter: http://twitter.com/robertpataki
* Blog: http://robertpataki.com
*/
/**
* CanvasLoader uses the HTML5 canvas element in modern browsers to create and animate the most popular preloader shapes (oval, spiral, rectangle, square and rounded rectangle).&lt;br/&gt;&lt;br/&gt;
* To start rendering and display the loader use the &lt;code&gt;show()&lt;/code&gt; method.
* @module CanvasLoader
**/
(function (window) {
&#x27;use strict&#x27;;
/**
* CanvasLoader is a JavaScript UI library that draws and animates circular preloaders using the Canvas HTML object.&lt;br/&gt;&lt;br/&gt;
* A CanvasLoader instance creates two canvas elements which are placed into a placeholder div (the id of the div has to be passed in the constructor). The second canvas is invisible and used for caching purposes only.&lt;br/&gt;&lt;br/&gt;
* If no id is passed in the constructor, the canvas objects are paced in the document directly.
* @class CanvasLoader
* @constructor
* @param {Object} target The target DOM element to place the spinner into
* @param {Object} [settings] Settings to customise the spinner instance
* @param {Number} [settings.diameter] The expected diameter
* @param {Number} [settings.density] The number of the shapes
* @param {Number} [settings.color] The color of the shapes
* @param {Number} [settings.range] The weight of the trail
* @param {Number} [settings.duration] The duration of 1 spin animation to completely go around
* @param {Number} [settings.shape] The shape type (oval, rect, square, roundRect)
* @param {String} [settings.id] The id of the CanvasLoader instance
*
*
**/
var CanvasLoader = function (target, settings) {
settings = settings || {};
this._init(target, settings);
};
var proto = CanvasLoader.prototype;
///
///
///
//////////////
//// Private fields
/////////////
///
///
///
/**
* The type of supported spinner shapes
* @property _shapes
* @private
* @type {Object}
*/
proto._shapes = [&#x27;oval&#x27;, &#x27;spiral&#x27;, &#x27;square&#x27;, &#x27;rect&#x27;, &#x27;roundRect&#x27;];
/**
* Regular expression for matching Hexadecimal colour values
* @property _colorRegEx
* @private
* @type {Object}
*/
proto._colorRegEx = /^\#([a-fA-F0-9]{6}|[a-fA-F0-9]{3})$/;
/**
* Check for canvas support
* @property _supportsCanvas
* @private
* @type {Boolean}
*/
proto._supportsCanvas = !!document.createElement(&#x27;canvas&#x27;).getContext;
/**
* Holds settings (this is updated with user settings)
* @property _settings
* @private
* @type {Object}
*/
proto._settings = {
shape: &#x27;oval&#x27;,
color: &#x27;#000000&#x27;,
diameter: 40,
range: 0.2,
density: 40,
duration: 1,
autoShow: true
};
/**
* Holds default settings
* @property _defaultSettings
* @private
* @type {Object}
*/
proto._defaultSettings = proto._settings;
/**
* The div we place the canvas object into
* @property _container
* @private
* @type {Object}
**/
proto._container = null;
/**
* The div we draw the shapes into
* @property _canvas
* @private
* @type {Object}
**/
proto._canvas = null;
/**
* The canvas context
* @property _context
* @private
* @type {Object}
**/
proto._context = null;
/**
* The canvas we use for caching
* @property _cacheCanvas
* @private
* @type {Object}
**/
proto._cacheCanvas = null;
/**
* The context of the cache canvas
* @property _cacheContext
* @private
* @type {Object}
**/
proto._cacheContext = null;
/**
* Adds a timer for the rendering
* @property _timer
* @private
* @type {Boolean}
**/
proto._timer = 0;
/**
* The current rotation degree of the spinner
* @property _currentDegree
* @private
* @type {Number}
**/
proto._currentDegree = 0;
/**
* The diameter of the loader
* @property _diameter
* @private
* @type {Number}
* @default 40
**/
proto._diameter = proto._settings.diameter;
/**
* The color of the loader shapes in RGB
* @property _cRGB
* @private
* @type {Object}
**/
proto._cRGB = {};
/**
* The color of the loader shapes in HEX
* @property _color
* @private
* @type {String}
* @default &#x27;#000000&#x27;
**/
proto._color = proto._settings.color;
/**
* The type of the loader shapes
* @property _shape
* @private
* @type String
* @default &#x27;oval&#x27;
**/
proto._shape = proto._settings.shape;
/**
* The number of shapes drawn on the loader canvas
* @property _density
* @private
* @type Number
* @default 40
**/
proto._density = proto._settings.density;
/**
* The amount of the modified shapes in percent.
* @property _range
* @private
* @type {Number}
**/
proto._range = proto._settings.range;
/**
* The duration of a 360 degree rotation in seconds
* @property _duration
* @private
* @type {Number}
**/
proto._duration = proto._settings.duration;
///
///
///
//////////////
//// Private methods
/////////////
///
///
///
///
/**
* Creates a new element with the tag and applies the passed properties on it
* @private
* @method proto._addElement
* @param tag {String} The tag to be created
* @param par {String} The DOM element the new element will be appended to
* @param opt {Object} Additional properties passed to the new DOM element
* @return {Object} The DOM element
*/
proto._addElement = function (tag, par, opt) {
var el = document.createElement(tag), n;
for (n in opt) {
el[n] = opt[n];
}
if(typeof par !== &#x27;undefined&#x27;) {
par.appendChild(el);
}
return el;
},
/**
* Sets the css properties on the element
* @private
* @method proto._setCSS
* @param el {Object} The DOM element to be styled
* @param opt {Object} The style properties
* @return {Object} The DOM element
*/
proto._setCSS = function (el, opt) {
for (var n in opt) { el.style[n] = opt[n]; }
return el;
},
/**
* Sets the attributes on the element
* @private
* @method proto._setAttribute
* @param el {Object} The DOM element to add the attributes to
* @param opt {Object} The attributes
* @return {Object} The DOM element
*/
proto._setAttribute = function (el, opt) {
for (var n in opt) { el.setAttribute(n, opt[n]); }
return el;
},
/**
* Returns if the browser supports CSS animations
* @private
* @method proto._supportsKeyframes
* @return {Boolean}
*/
proto._supportsKeyframes = function () {
var el = document.body.appendChild(document.createElement(&#x27;div&#x27;));
var result = false;
var prefs = (&#x27;webkit moz o ms khtml&#x27;).split(&#x27; &#x27;);
for(var i = 0; i &lt;= prefs.length; i++) {
var pref = i === prefs.length ? &#x27;animation&#x27; : prefs[i] + &#x27;Animation&#x27;;
if(typeof el.style[pref] !== &#x27;undefined&#x27;) {
result = true;
break;
}
}
return result;
},
/**
* Transforms the cache canvas before drawing
* @private
* @method proto._transformCachedCanvasContext
* @param canvasContext {Object} The canvas context to be transformed
* @param x {Number} x translation
* @param y {Number} y translation
* @param rads {Number} Rotation in radians
*/
proto._transformCachedCanvasContext = function(canvasContext, x, y, rads) {
canvasContext.save();
canvasContext.translate(x, y);
canvasContext.rotate(rads);
canvasContext.translate(-x, -y);
canvasContext.beginPath();
};
/**
* Initialization method
* @method _init
* @private
* @param target {Object} The target DOM element to place the spinner into
* @param settings {Object} Settings to customise the spinner instance
**/
proto._init = function (target, settings) {
var args = this._settings;
this.dad = target;
// Create the parent div of the loader instance
this._container = proto._addElement(&#x27;div&#x27;, this.dad, {className: &#x27;canvasloader&#x27;});
// Create the canvas and cache canvas with context
if (this._supportsCanvas) {
this._canvas = proto._addElement(&#x27;canvas&#x27;, this._container);
this._context = this._canvas.getContext(&#x27;2d&#x27;);
this._cacheCanvas = proto._setCSS(proto._addElement(&#x27;canvas&#x27;, this._container), { display: &#x27;none&#x27; });
this._cacheContext = this._cacheCanvas.getContext(&#x27;2d&#x27;);
} else {
console.warn(&#x27;[CanvasLoader] - Browser won\&#x27;t support canvas, bye!&#x27;);
}
// Add the keyframe animation definition to the &lt;head&gt;
if(this._supportsKeyframes() &amp;&amp; !document.getElementById(&#x27;cl-sheet&#x27;)) {
var sheet = this._addElement(&#x27;style&#x27;, document.getElementsByTagName(&quot;head&quot;)[0]);
this._setAttribute(sheet, {id: &#x27;cl-sheet&#x27;});
sheet = document.getElementById(&#x27;cl-sheet&#x27;);
var keyframePrefixes = [&#x27;@-webkit-keyframes&#x27;, &#x27;@-moz-keyframes&#x27;, &#x27;@-o-keyframes&#x27;, &#x27;@keyframes&#x27;];
var keyFrameRule = &#x27;from {transform: rotateZ(0deg);} to {transform: rotateZ(360deg);}&#x27;;
for (var i = 0; i &lt; keyframePrefixes.length; i++) {
var prefixBegins = keyframePrefixes[i].indexOf(&#x27;@&#x27;) + 1;
var prefixEnds = keyframePrefixes[i].indexOf(&#x27;-keyframes&#x27;) + 1;
var prefix = keyframePrefixes[i].substring(prefixBegins, prefixEnds);
var re = new RegExp(&#x27;transform&#x27;, &#x27;g&#x27;);
var rule = prefix !== &#x27;@&#x27; ? keyFrameRule.replace(re, prefix + &#x27;transform&#x27;) : keyFrameRule;
sheet.innerHTML += &#x27;\n\n&#x27; + keyframePrefixes[i] + &#x27; cl-spin {&#x27; + rule + &#x27;}&#x27;;
}
}
// Set up shapes
var shape = settings.shape || args.shape;
for (var i = 0; i &lt; this._shapes.length; i++) {
if (shape === this._shapes[i]) {
this._shape = shape;
break;
}
}
// Set up diameter
var diameter = settings.diameter || args.diameter;
this._diameter = diameter;
this._setCSS(this.dad, {&#x27;marginLeft&#x27;: Math.round(diameter * -0.5) + &#x27;px&#x27;});
// Set up density
var density = settings.density || args.density;
this._density = Math.round(Math.abs(density));
this._currentDegree = 0;
this._degreeBlock = 360 / this._density;
// Set up colour
var color = settings.color;
this._color = this._colorRegEx.test(color) ? color : args.color;
this._cRGB = this._getRGB(this._color);
// Set up range
this._range = Math.abs(settings.range || args.range);
// Set up spin duration
this._duration = Math.abs(settings.duration || args.duration);
this._renderInterval = Math.round(this._duration * 1000 / this._density);
// Initial rendering
this._draw();
//Hides the preloader
this._setCSS(this._container, {visibility: &#x27;hidden&#x27;, display: &#x27;none&#x27;});
// Show automatically if specifically required by the user
var autoShow = settings.autoShow || args.autoShow;
if(autoShow) {
this.show();
}
};
/**
* Return the RGB values of the passed color
* @private
* @method _getRGB
* @param color {String} The HEX color value to be converted to RGB
*/
proto._getRGB = function (c) {
c = c.charAt(0) === &#x27;#&#x27; ? c.substring(1, 7) : c;
return {r: parseInt(c.substring(0, 2), 16), g: parseInt(c.substring(2, 4), 16), b: parseInt(c.substring(4, 6), 16) };
};
/**
* Return the default settings
* @private
* @method _getDefaults
*/
proto._getDefaults = function () {
return this._defaultSettings;
};
/**
* Draw the shapes on the canvas
* @private
* @method _draw
*/
proto._draw = function () {
var i = 0, size, w, h, x, y, ang, rads, rad, de = this._density, animBits = Math.round(de * this._range), bitMod, minBitMod = 0, d = 1000, c = this._cacheContext, di = this._diameter, e = 0.47, pr = 4 || 1;
c.clearRect(0, 0, d, d);
this._setAttribute(this._canvas, {width: di * pr, height: di * pr});
this._setCSS(this._canvas, {width: di + &#x27;px&#x27;, height: di + &#x27;px&#x27;});
this._setAttribute(this._cacheCanvas, {width: di * pr, height: di * pr});
this._setCSS(this._cacheCanvas, {width: di + &#x27;px&#x27;, height: di + &#x27;px&#x27;});
c.scale(pr, pr);
this._context.scale(pr, pr);
while (i &lt; de) {
bitMod = i &lt;= animBits ? 1 - ((1 - minBitMod) / animBits * i) : bitMod = minBitMod;
ang = 270 - 360 / de * i;
rads = ang / 180 * Math.PI;
c.fillStyle = &#x27;rgba(&#x27; + this._cRGB.r + &#x27;,&#x27; + this._cRGB.g + &#x27;,&#x27; + this._cRGB.b + &#x27;,&#x27; + bitMod.toString() + &#x27;)&#x27;;
switch (this._shape) {
case this._shapes[0]:
case this._shapes[1]:
size = di * 0.07;
x = di * e + Math.cos(rads) * (di * e - size) - di * e;
y = di * e + Math.sin(rads) * (di * e - size) - di * e;
c.beginPath();
if (this._shape === this._shapes[1]) { c.arc(di * 0.5 + x, di * 0.5 + y, size * bitMod, 0, Math.PI * 2, false); } else { c.arc(di * 0.5 + x, di * 0.5 + y, size, 0, Math.PI * 2, false); }
break;
case this._shapes[2]:
size = di * 0.12;
x = Math.cos(rads) * (di * e - size) + di * 0.5;
y = Math.sin(rads) * (di * e - size) + di * 0.5;
this._transformCachedCanvasContext(c, x, y, rads);
c.fillRect(x, y - size * 0.5, size, size);
break;
case this._shapes[3]:
case this._shapes[4]:
w = di * 0.3;
h = w * 0.27;
x = Math.cos(rads) * (h + (di - h) * 0.13) + di * 0.5;
y = Math.sin(rads) * (h + (di - h) * 0.13) + di * 0.5;
this._transformCachedCanvasContext(c, x, y, rads);
if(this._shape === this._shapes[3]) {
c.fillRect(x, y - h * 0.5, w, h);
} else {
rad = h * 0.55;
c.moveTo(x + rad, y - h * 0.5);
c.lineTo(x + w - rad, y - h * 0.5);
c.quadraticCurveTo(x + w, y - h * 0.5, x + w, y - h * 0.5 + rad);
c.lineTo(x + w, y - h * 0.5 + h - rad);
c.quadraticCurveTo(x + w, y - h * 0.5 + h, x + w - rad, y - h * 0.5 + h);
c.lineTo(x + rad, y - h * 0.5 + h);
c.quadraticCurveTo(x, y - h * 0.5 + h, x, y - h * 0.5 + h - rad);
c.lineTo(x, y - h * 0.5 + rad);
c.quadraticCurveTo(x, y - h * 0.5, x + rad, y - h * 0.5);
}
break;
}
c.closePath();
c.fill();
c.restore();
++i;
}
this._render(true);
};
proto._render = function(initialRendering) {
if(this._supportsKeyframes()) {
this._context.drawImage(this._cacheCanvas, 0, 0, this._diameter, this._diameter);
var animPrefixes = [&#x27;webkitAnimation&#x27;, &#x27;mozAnimation&#x27;, &#x27;oAnimation&#x27;, &#x27;animation&#x27;];
var animProps = &#x27;cl-spin &#x27; + this._duration + &#x27;s&#x27; + &#x27; steps(&#x27; + this._density + &#x27;) infinite&#x27;;
var animObject = {};
for (var i = 0; i &lt; animPrefixes.length; i++) {
animObject[animPrefixes[i]] = animProps;
}
this._setCSS(this._canvas, animObject);
} else {
var self = this;
if(initialRendering) {
this._currentDegree = 0;
} else {
this._currentDegree += this._degreeBlock;
if(this._currentDegree &gt; 360) {
this._currentDegree -= 360;
}
}
this._context.clearRect(0, 0, this._diameter, this._diameter);
this._transformCachedCanvasContext(this._context, this._diameter * 0.5, this._diameter * 0.5, this._currentDegree / 180 * Math.PI);
this._context.drawImage(this._cacheCanvas, 0, 0, this._diameter, this._diameter);
this._context.restore();
if (!self._timer) {
self._timer = setInterval(function () { self._render(); }, self._renderInterval);
}
}
}
///
///
///
//////////////
//// Public methods
/////////////
///
///
///
/**
* Return argument value by key if defined
* @param key {String} The key to look up
* @return The value of the key
* @method get
*/
proto.get = function(key) {
if(key === &#x27;defaults&#x27;) {
return this._getDefaults();
}
if(this._settings.hasOwnProperty(key) &amp;&amp; this.hasOwnProperty(&#x27;_&#x27; + key)) {
return this[&#x27;_&#x27; + key];
}
};
/**
* Shows the rendering of the loader animation
* @method show
* @chainable
* @return {CanvasLoader} The CanvasLoader instance
*/
proto.show = function () {
this._setCSS(this._container, {visibility: &#x27;visible&#x27;, display: &#x27;block&#x27;});
this._render(true);
return self;
};
/**
* Stops the rendering of the loader animation and hides the loader
* @method hide
* @chainable
* @return {CanvasLoader} The CanvasLoader instance
*/
proto.hide = function () {
// TODO - we probably will need to remove the CSS animation when hiding the spinner
if(this._timer) {
clearInterval(this._timer);
this._timer = null;
this._setCSS(this._container, {visibility: &#x27;hidden&#x27;, display: &#x27;none&#x27;});
}
return this;
};
/**
* Clears the DOM and resets all params
* @method destruct
*/
proto.destruct = function () {
this.hide();
this.dad.removeChild(this._container);
for (var n in this) {
delete this[n];
this[n] = null;
}
};
window.CanvasLoader = CanvasLoader;
}(window));
</pre>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<script src="../assets/vendor/prettify/prettify-min.js"></script>
<script>prettyPrint();</script>
<script src="../assets/js/yui-prettify.js"></script>
<script src="../assets/../api.js"></script>
<script src="../assets/js/api-filter.js"></script>
<script src="../assets/js/api-list.js"></script>
<script src="../assets/js/api-search.js"></script>
<script src="../assets/js/apidocs.js"></script>
</body>
</html>