Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

implement vector image skipping with tests

  • Loading branch information...
commit 2f01d58e9a5732b2a71e6a6d9725041121dc2c8d 1 parent d91247a
@benatkin authored
View
109 retinajs/README.md
@@ -0,0 +1,109 @@
+# retina.js
+
+### JavaScript and LESS helpers for rendering high-resolution image variants
+
+retina.js makes it easy to serve high-resolution images to devices with retina displays
+
+## How it works
+
+When your users load a page, retina.js checks each image on the page to see if there is a high-resolution version of that image on your server. If a high-resolution variant exists, the script will swap in that image in-place.
+
+The script assumes you use Apple's prescribed high-resolution modifier (@2x) to denote high-resolution image variants on your server.
+
+For example, if you have an image on your page that looks like this:
+
+ <img src="/images/my_image.png" />
+
+The script will check your server to see if an alternative image exists at this path:
+
+ "/images/my_image@2x.png"
+
+##How to use
+
+###JavaScript
+
+The JavaScript helper script automatically replaces images on your page with high-resolution variants (if they exist). To use it, download the script and include it at the bottom of your page.
+
+1. Place the retina.js file on your server
+2. Include the script on your page (put it at the bottom of your template, before your closing \</body> tag)
+
+``` html
+<script type="text/javascript" src="/scripts/retina.js"></script>
+```
+
+###LESS
+
+The LESS CSS mixin is a helper for applying high-resolution background images in your stylesheet. You provide it with an image path and the dimensions of the original-resolution image. The mixin creates a media query spefically for Retina displays, changes the background image for the selector elements to use the high-resolution (@2x) variant and applies a background-size of the original image in order to maintain proper dimensions. To use it, download the mixin, import or include it in your LESS stylesheet, and apply it to elements of your choice.
+
+*Syntax:*
+
+``` less
+.at2x(@path, [optional] @width: auto, [optional] @height: auto);
+```
+
+*Steps:*
+
+1. Add the .at2x() mixin from retina.less to your LESS stylesheet (or reference it in an @import statement)
+2. In your stylesheet, call the .at2x() mixin anywhere instead of using background-image
+
+This:
+
+``` less
+.logo {
+ .at2x('/images/my_image.png', 200px, 100px);
+}
+```
+
+Will compile to:
+
+``` less
+.logo {
+ background-image: url('/images/my_image.png');
+}
+
+@media all and (-webkit-min-device-pixel-ratio: 1.5) {
+ .logo {
+ background-image: url('/images/my_image@2x.png');
+ background-size: 200px 100px;
+ }
+}
+```
+
+##How to test
+
+We use [mocha](http://visionmedia.github.com/mocha/) for unit testing with [should](https://github.com/visionmedia/should.js) assertions. Install mocha and should by running `npm install`.
+
+To run the test suite:
+
+``` bash
+$ npm test
+```
+
+Use [http-server](https://github.com/nodeapps/http-server) for node.js to test it. To install, run `npm install -g http-server`.
+
+If you've updated `retina.js` be sure to copy it from `src/retina.js` to `test/functional/public/retina.js`.
+
+To start the server, run:
+
+``` bash
+$ cd test/functional && http-server
+```
+
+Then navigate your browser to [http://localhost:8080](http://localhost:8080)
+
+After that, open up `test/functional/public/index.html` in your editor, and try commenting out the line that spoofs retina support, and reloading it.
+
+
+#License
+
+(MIT License)
+
+Copyright (C) 2012 [Imulus](http://imulus.com)
+
+Copyright (C) 2012 Ben Atkin
+
+Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), 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 "AS IS", 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.
View
147 retinajs/retina.0.0.2.js
@@ -0,0 +1,147 @@
+// retina.js
+// Source for retina.js, a high-resolution image swapper (http://www.retinajs.com)
+
+(function() {
+
+var root = (typeof exports == 'undefined' ? window : exports);
+
+function RetinaImagePath(path) {
+ this.path = path;
+ // Split the file extension off the image path,
+ // and put it back together with @2x before the extension.
+ // "/path/to/image.png" => "/path/to/image@2x.png"
+ var path_segments = this.path.split('.');
+ var path_without_extension = path_segments.slice(0, (path_segments.length - 1)).join(".");
+ var extension = path_segments[path_segments.length - 1];
+ this.at_2x_path = path_without_extension + "@2x." + extension;
+}
+
+root.RetinaImagePath = RetinaImagePath;
+
+// Class variable [Array]
+// cache of files we've checked on the server
+RetinaImagePath.confirmed_paths = [];
+
+// Function to test if image is external
+RetinaImagePath.prototype.is_external = function() {
+ return !!(this.path.match(/^https?\:/i) && !this.path.match('//' + document.domain) )
+}
+
+RetinaImagePath.prototype.check_2x_variant = function(callback) {
+ var http, that = this;
+ if (this.is_external()) {
+ // If the image path is on an external server,
+ // exit early to avoid cross-domain ajax errors
+ return callback(false);
+ } else if (this.at_2x_path in RetinaImagePath.confirmed_paths) {
+ // If we have already checked and confirmed that
+ // the @2x variant exists, then just return true
+ return callback(true);
+ } else {
+ // Otherwise, prepare an AJAX request for the HEAD only.
+ // We don't need a full request because we're only
+ // checking to see if the @2x version exists on the server
+ http = new XMLHttpRequest;
+ http.open('HEAD', this.at_2x_path);
+ http.onreadystatechange = function() {
+ if (http.readyState != 4) {
+ return callback(false);
+ }
+
+ // If we get an A-OK from the server,
+ // push file path onto array of confirmed files
+ if (http.status >= 200 && http.status <= 399) {
+ RetinaImagePath.confirmed_paths.push(that.at_2x_path);
+ return callback(true);
+ } else {
+ return callback(false);
+ }
+ }
+ http.send();
+ }
+}
+
+function RetinaImage(el) {
+ this.el = el;
+ this.path = new RetinaImagePath(this.el.getAttribute('src'));
+ var that = this;
+ this.path.check_2x_variant(function(hasVariant) {
+ if (hasVariant) that.swap();
+ });
+}
+
+root.RetinaImage = RetinaImage;
+
+// Method for swapping in a new image path
+// Applies the dimensions of the existing image
+// to the image with the new image path
+RetinaImage.prototype.swap = function(path) {
+ var that = this, hidden = false, width, height;
+
+ if (typeof path == 'undefined') path = this.path.at_2x_path;
+
+ // We wrap this in a named self-executer so we can reference
+ // it in a setTimeout if the image has not loaded yet.
+ function load() {
+ if (! that.el.complete) {
+ // Check that the image has loaded.
+ // We need to wait for the image to load to grab proper dimensions.
+
+ // If it has not, try again in a few milliseconds.
+ // We've found 5ms to be the fastest we can crank this up
+ // and still have the script detect image loads reliably and efficiently.
+ setTimeout(load, 5);
+ } else {
+ // If offsetWidth is 0, the image is probably hidden
+ width = that.el.offsetWidth;
+ if (!width || width == "0") {
+ // try to get width from the image attribute
+ width = el.getAttribute('width')
+ if (!width || width == "0") {
+ hidden = true;
+ }
+ }
+
+ // same for height
+ height = that.el.offsetHeight;
+ if (!height || height == "0") {
+ // try to get width from the image attribute
+ height = el.getAttribute('height')
+ if (!height || height == "0") {
+ hidden = true;
+ }
+ }
+
+ // Once the the image has loaded we know we
+ // can grab the proper dimensions of the original image
+ // and go ahead and swap in the new image path and apply the dimensions
+ if (! hidden) {
+ that.el.setAttribute('width', width);
+ that.el.setAttribute('height', height);
+ that.el.setAttribute('src', path);
+ }
+ }
+ }
+ load();
+}
+
+// First check that we're on a retina device.
+// We don't even want this guy executing if we're not.
+// Bind everything to the window object's onload.
+// This helps wait for the images to get loaded into the DOM.
+
+if (root.devicePixelRatio > 1) {
+ window.onload = function() {
+ var images = document.getElementsByTagName("img"), retinaImages = [], i, image, ext;
+ for (i = 0; i < images.length; i++) {
+ image = images[i];
+ ext = (image.src || '').split('.').pop();
+ console.log(ext);
+ if (typeof ext == 'string' && ext.toLowerCase() != 'svg') {
+ retinaImages.push(new RetinaImage(image));
+ }
+ }
+ }
+}
+
+})();
View
3  retinajs/retina.0.0.2.min.js
@@ -0,0 +1,3 @@
+// retina.js
+// Source for retina.js, a high-resolution image swapper (http://www.retinajs.com)
+(function(){function t(e){this.path=e;var t=this.path.split("."),n=t.slice(0,t.length-1).join("."),r=t[t.length-1];this.at_2x_path=n+"@2x."+r}function n(e){this.el=e,this.path=new t(this.el.getAttribute("src"));var n=this;this.path.check_2x_variant(function(e){e&&n.swap()})}var e=typeof exports=="undefined"?window:exports;e.RetinaImagePath=t,t.confirmed_paths=[],t.prototype.is_external=function(){return!!this.path.match(/^https?\:/i)&&!this.path.match("//"+document.domain)},t.prototype.check_2x_variant=function(e){var n,r=this;if(this.is_external())return e(!1);if(this.at_2x_path in t.confirmed_paths)return e(!0);n=new XMLHttpRequest,n.open("HEAD",this.at_2x_path),n.onreadystatechange=function(){return n.readyState!=4?e(!1):n.status>=200&&n.status<=399?(t.confirmed_paths.push(r.at_2x_path),e(!0)):e(!1)},n.send()},e.RetinaImage=n,n.prototype.swap=function(e){function s(){if(!t.el.complete)setTimeout(s,5);else{r=t.el.offsetWidth;if(!r||r=="0"){r=el.getAttribute("width");if(!r||r=="0")n=!0}i=t.el.offsetHeight;if(!i||i=="0"){i=el.getAttribute("height");if(!i||i=="0")n=!0}n||(t.el.setAttribute("width",r),t.el.setAttribute("height",i),t.el.setAttribute("src",e))}}var t=this,n=!1,r,i;typeof e=="undefined"&&(e=this.path.at_2x_path),s()},e.devicePixelRatio>1&&(window.onload=function(){var e=document.getElementsByTagName("img"),t=[],r,i,s;for(r=0;r<e.length;r++)i=e[r],s=(i.src||"").split(".").pop(),console.log(s),typeof s=="string"&&s.toLowerCase()!="svg"&&t.push(new n(i))})})();
View
12 retinajs/retina.less
@@ -0,0 +1,12 @@
+// retina.less
+// A helper mixin for applying high-resolution background images (http://www.retinajs.com)
+
+.at2x(@path, @w: auto, @h: auto) {
+ background-image: url(@path);
+ @at2x_path: ~`"@{path}".split('.').slice(0, "@{path}".split('.').length - 1).join(".") + "@2x" + "." + "@{path}".split('.')["@{path}".split('.').length - 1]`;
+
+ @media all and (-webkit-min-device-pixel-ratio : 1.5) {
+ background-image: url(@at2x_path);
+ background-size: @w @h;
+ }
+}
View
16 src/retina.js
@@ -27,12 +27,20 @@ RetinaImagePath.prototype.is_external = function() {
return !!(this.path.match(/^https?\:/i) && !this.path.match('//' + document.domain) )
}
+RetinaImagePath.prototype.is_vector = function() {
+ return this.path.match(/\.svg$/i);
+}
+
RetinaImagePath.prototype.check_2x_variant = function(callback) {
var http, that = this;
if (this.is_external()) {
// If the image path is on an external server,
// exit early to avoid cross-domain ajax errors
return callback(false);
+ } else if (this.is_vector()) {
+ // this image is a vector so it should scale
+ // nicely without our help
+ return callback(false);
} else if (this.at_2x_path in RetinaImagePath.confirmed_paths) {
// If we have already checked and confirmed that
// the @2x variant exists, then just return true
@@ -132,14 +140,10 @@ RetinaImage.prototype.swap = function(path) {
if (root.devicePixelRatio > 1) {
window.onload = function() {
- var images = document.getElementsByTagName("img"), retinaImages = [], i, image, ext;
+ var images = document.getElementsByTagName("img"), retinaImages = [], i, image;
for (i = 0; i < images.length; i++) {
image = images[i];
- ext = (image.src || '').split('.').pop();
- console.log(ext);
- if (typeof ext == 'string' && ext.toLowerCase() != 'svg') {
- retinaImages.push(new RetinaImage(image));
- }
+ retinaImages.push(new RetinaImage(image));
}
}
}
View
22 test/functional/public/flag.svg
@@ -0,0 +1,22 @@
+<?xml version="1.0" encoding="iso-8859-1"?>
+<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.0//EN" "http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd">
+<!-- Creator: CorelDRAW -->
+<svg xmlns="http://www.w3.org/2000/svg" xmlns:odm="http://product.corel.com/CGS/11/cddns/" xml:space="preserve" width="600px" height="358px" style="shape-rendering:geometricPrecision; text-rendering:geometricPrecision; image-rendering:optimizeQuality; fill-rule:evenodd"
+ viewBox="0 0 600 358">
+ <defs>
+ <style type="text/css">
+ <![CDATA[
+ .fil0 {fill:#002868}
+ .fil3 {fill:#bf0a30}
+ .fil1 {fill:#ffd700}
+ .fil2 {fill:#FFFFFF}
+ ]]>
+ </style>
+ </defs>
+ <path class="fil0" d="M0 0l600 0 0 358 -600 0 0 -358z"/>
+ <g id="Layer 1">
+ <circle class="fil1" cx="303" cy="99" r="65"/>
+ <path class="fil2" d="M0 216l0 144 600 0 0 -144 -115 -126 -182 193 -181 -193 -122 126z"/>
+ <path class="fil3" d="M0 283l0 77 600 0 0 -77 -115 -124 -182 197 -181 -197 -122 124z"/>
+ </g>
+</svg>
View
1  test/functional/public/index.html
@@ -26,6 +26,7 @@
<img src="google.png" /> <!-- It will find the @2x version of this in the confirmed_paths cache because it is a duplicate -->
<img src="google@1x.png" /> <!-- This will not be replaced with a retina version-->
<img src="https://www.google.com/logos/2012/doisneau12-hp.jpg" />
+ <img src="flag.svg" />
<div class="responsive">
<img src="ipad_hero.jpeg" />
View
8 test/retina_image_path.test.js
@@ -88,6 +88,14 @@ describe('RetinaImagePath', function() {
});
});
+ it('should callback with false when img is an svg', function(done) {
+ path = new RetinaImagePath("/images/some_image.svg");
+ path.check_2x_variant(function(hasVariant) {
+ hasVariant.should.equal(false);
+ done();
+ });
+ });
+
it('should callback with false when remote at2x image does not exist', function(done) {
XMLHttpRequest.status = 404; // simulate a failing request
path = new RetinaImagePath("/images/some_image.png");
Please sign in to comment.
Something went wrong with that request. Please try again.