Archive

Archive for the ‘JavaScript’ Category

Canvas Tile System

September 15th, 2011 No comments

Here’s something quick that I put together to see how easily I could create a Tile System (as in 2d sprite map for games) using JavaScript and Canvas.

First I set out to create a system for loading, caching, and retrieving the tiles. Here’s what I came up with:

// Allows you to load image sprite and then make cached tiles
// that can be retrieved
var TileLibrary = function (img) {
  var oTileLibrary = {},
      elCanvas = document.createElement('canvas'),
      cxCanvas = elCanvas.getContext('2d');
 
  elCanvas.width  = img.width;
  elCanvas.height = img.height;
  cxCanvas.drawImage(img, 0, 0, img.width, img.height);
 
  return {
    makeType: function (name, x, y, width, height) {
      oTileLibrary[name] = cxCanvas.getImageData(x, y, width, height);
    },
    getTileData: function (name) {
      return oTileLibrary[name];
    }
  };
};

 

This allows me to take an Image object and turn pieces of it into data that canvas can understand. Usage would look something like this:

// img is a preloaded image object
var oTileLibrary = new TileLibrary(img);
 
// cuts out a chunk of the image at (0, 0) with dimensions 64x64 and caches it
oTileLibrary.makeType("FloorTile", 0, 0, 64, 64);
 
// gets the ImageData out of cache and ready to be dumped into a canvas
var tFloorTile = oTileLibrary.getTileData("FloorTile");
 
// inserts that floor tile into its final destination
myCanvas.putImageData(tFloorTile, 0, 0);

 

I ended up borrowing this image for my prototype:
Desert Sprite Map

( http://www.lostgarden.com/2006/02/250-free-handdrawn-textures.html )

 

I cut out the third tile and the fourth tile, and arranged them in a 3×3 grid, with the middle tile being the little circle looking thing.

Check out the sample here: Tile System Prototype

Share and Enjoy:
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Mixx
  • Google Bookmarks
  • LinkedIn
  • Live
  • MySpace
  • Reddit
  • StumbleUpon
Categories: JavaScript Tags:

Canvas Pixel Manipulation a’ la Quick and Dirty

September 9th, 2011 No comments

In a recent prototype I attempted to load in a PNG onto a canvas, change the image to a silhouette, as well as create a desaturated version, cache all three (including the initial state) sets of pixel data, and swap them out interchangeably. Then I wanted to spit the data back out into something I could incorporate into the DOM.

Here’s what I came up with: Canvas Pixel Manipulation

Share and Enjoy:
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Mixx
  • Google Bookmarks
  • LinkedIn
  • Live
  • MySpace
  • Reddit
  • StumbleUpon
Categories: JavaScript Tags:

JavaScript Timer Countdown

August 2nd, 2011 No comments

Working on a new game. Wrote this TimerCountdown object for a Timer in the game. Works pretty well, still not fully tested.

var TimerCountdown = function() {
  var oOnZero     = function(){},
      oOnUpdate   = function(){},
      oTimer,
      iCurTime    = 0;
 
  function CreateTimer() {
    oTimer = setInterval(IterateTimer, 1000)
  }
 
  function DestroyTimer() {
    clearInterval( oTimer );
  }
 
  function IterateTimer() {
    iCurTime = iCurTime - 1;
    oOnUpdate({
      Seconds: iCurTime,
      Minutes: parseInt( iCurTime / 60 ),
      Hours: parseInt( iCurTime / 60 / 60 )
    });
 
    if( iCurTime <= 0 ) {
      DestroyTimer();
      oOnZero();
    }
  }
 
  return {
    SetTime: function( iSeconds ) {
      iCurTime = iSeconds;
    },
    Start: function() {
      CreateTimer();
    },
    Stop: function() {
      DestroyTimer();
    },
    Time: function() {
      return iCurTime;
    },
    Add: function( iSeconds ) {
      iCurTime = iCurTime + iSeconds;
    },
    Subtract: function( iSeconds ) {
      iCurTime = iCurTime - iSeconds;
    },
    OnUpdate: function( cbFunction ) {
      oOnUpdate = cbFunction;
    },
    OnZero: function( cbFunction ) {
      oOnZero = cbFunction;
    }
  };
};
Share and Enjoy:
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Mixx
  • Google Bookmarks
  • LinkedIn
  • Live
  • MySpace
  • Reddit
  • StumbleUpon
Categories: JavaScript Tags: , ,

JavaScript Replace All

March 25th, 2011 No comments

Here’s my version of the replaceAll() method for JavaScript. I doubt it’s faster than RegEx, but it was certainly fun to make. :)

String.prototype.replaceAll = function(s, r, n) {
	if( this.toString().indexOf(s) < n ) n = 0;
	if( !n ) return this.toString().split( s ).join( r );
 
	var j = this.toString();
	while( n-- ) {
		j = j.replace( s, r );
	}
 
	return j;
}
 
var TestString = "I Love My Pie So Much, Don't You?";
 
// Usage
console.log( TestString.replace("o", "*") );
console.log( TestString.replaceAll("o", "*", 2) );
Share and Enjoy:
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Mixx
  • Google Bookmarks
  • LinkedIn
  • Live
  • MySpace
  • Reddit
  • StumbleUpon
Categories: JavaScript Tags:

Text to Pixel Font!

January 16th, 2011 No comments

So, this is a silly little proof of concept I came up with to kill 20 minutes in between projects. Takes regular text and turns it into 1px sized divs. That’s right, the div’s actually form the pixels of each letter! :D Awesome, right!? Check it out!

jsTexty Example

How’s it done? Easy:
* Get the text of an element
* Move through it, 1 character at a time
* Match the character with a pattern (currently only supports lowercase)
* Convert the pattern to markup
* Replace the text with excessive amounts of html :D

$(document).ready(function() {
    var jsTexty = {};
 
    jsTexty.Make = function(e) {
        var strLetterString = $(e).text();
        var strReplaceHtml = '';
 
        for(var i = 0; i<strLetterString.length; i++) {
            var strThisLetter = strLetterString.substr(i,1);
            var arrLetterCode = jsTexty.GetLetterCode(strThisLetter);
                strReplaceHtml += jsTexty.LetterCodeToHtml(arrLetterCode);
        }
 
        $(e).html(strReplaceHtml + '<div class="clear"></div>');
    };
 
    jsTexty.LetterCodeToHtml = function(arrLetterCode) {
        var strReplaceHtml = '<div class="lbBlock">';
        for(var i = 0; i<arrLetterCode.length; i++) {
            var strThisRow = arrLetterCode[i];
            for(var j = 0; j<strThisRow; j++) {
                var strThisLetterBlock = strThisRow.substr(j,1);
                if(strThisLetterBlock==='1') {
                    strReplaceHtml += '<div class="lbSolid"></div>';
                }
                if(strThisLetterBlock==='0') {
                    strReplaceHtml += '<div class="lbEmpty"></div>';
                }
            }
            strReplaceHtml+='<div class="clear"></div>';
        }
        return strReplaceHtml + '</div>';
    }
 
    jsTexty.GetLetterCode = function(strSingleLetter) {
        switch(strSingleLetter) {
            case ' ':
                var arrLetterCode = [
                '0000',
                '0000',
                '0000',
                '0000',
                '0000'
                ];
                break;
            case 'a':
                var arrLetterCode = [
                '0110',
                '1001',
                '1111',
                '1001',
                '1001'
                ];
                break;
            case 'b':
                var arrLetterCode = [
                '1110',
                '1001',
                '1110',
                '1001',
                '1110'
                ];
                break;
            case 'c':
                var arrLetterCode = [
                '0111',
                '1000',
                '1000',
                '1000',
                '0111'
                ];
                break;
            case 'd':
                var arrLetterCode = [
                '1110',
                '1001',
                '1001',
                '1001',
                '1110'
                ];
                break;
            case 'e':
                var arrLetterCode = [
                '1111',
                '1000',
                '1110',
                '1000',
                '1111'
                ];
                break;
            case 'f':
                var arrLetterCode = [
                '1111',
                '1000',
                '1110',
                '1000',
                '1000'
                ];
                break;
            case 'g':
                var arrLetterCode = [
                '0111',
                '1000',
                '1011',
                '1001',
                '0111'
                ];
                break;
            case 'h':
                var arrLetterCode = [
                '1001',
                '1001',
                '1111',
                '1001',
                '1001'
                ];
                break;
            case 'i':
                var arrLetterCode = [
                '111',
                '010',
                '010',
                '010',
                '111'
                ];
                break;
            case 'j':
                var arrLetterCode = [
                '0001',
                '0001',
                '0001',
                '1001',
                '0110'
                ];
                break;
            case 'k':
                var arrLetterCode = [
                '1001',
                '1010',
                '1100',
                '1010',
                '1001'
                ];
                break;
            case 'l':
                var arrLetterCode = [
                '1000',
                '1000',
                '1000',
                '1000',
                '1111'
                ];
                break;
            case 'm':
                var arrLetterCode = [
                '10001',
                '11011',
                '10101',
                '10001',
                '10001'
                ];
                break;
            case 'n':
                var arrLetterCode = [
                '10001',
                '11001',
                '10101',
                '10011',
                '10001'
                ];
                break;
            case 'o':
                var arrLetterCode = [
                '0110',
                '1001',
                '1001',
                '1001',
                '0110'
                ];
                break;
            case 'p':
                var arrLetterCode = [
                '1110',
                '1001',
                '1110',
                '1000',
                '1000'
                ];
                break;
            case 'q':
                var arrLetterCode = [
                '0000',
                '0110',
                '1001',
                '0111',
                '0001'
                ];
                break;
            case 'r':
                var arrLetterCode = [
                '1110',
                '1001',
                '1110',
                '1001',
                '1001'
                ];
                break;
            case 's':
                var arrLetterCode = [
                '0111',
                '1100',
                '0110',
                '0011',
                '1110'
                ];
                break;
            case 't':
                var arrLetterCode = [
                '11111',
                '00100',
                '00100',
                '00100',
                '00100'
                ];
                break;
            case 'u':
                var arrLetterCode = [
                '1001',
                '1001',
                '1001',
                '1001',
                '0110'
                ];
                break;
            case 'v':
                var arrLetterCode = [
                '10001',
                '10001',
                '01010',
                '01010',
                '00100'
                ];
                break;
            case 'w':
                var arrLetterCode = [
                '10101',
                '10101',
                '10101',
                '10101',
                '01010'
                ];
                break;
            case 'x':
                var arrLetterCode = [
                '10001',
                '01010',
                '00100',
                '01010',
                '10001'
                ];
                break;
            case 'y':
                var arrLetterCode = [
                '10001',
                '01010',
                '00100',
                '00100',
                '00100'
                ];
                break;
            case 'z':
                var arrLetterCode = [
                '1111',
                '0001',
                '0010',
                '0100',
                '1111'
                ];
                break;
            case '.':
                var arrLetterCode = [
                '000',
                '000',
                '000',
                '110',
                '110'
                ];
                break;
            case ',':
                var arrLetterCode = [
                '000',
                '000',
                '000',
                '110',
                '010'
                ];
                break;
            case '!':
                var arrLetterCode = [
                '010',
                '010',
                '010',
                '000',
                '010'
                ];
                break;
            case '(':
                var arrLetterCode = [
                '010',
                '100',
                '100',
                '100',
                '010'
                ];
                break;
            case ')':
                var arrLetterCode = [
                '010',
                '001',
                '001',
                '001',
                '010'
                ];
                break;
            case '?':
                var arrLetterCode = [
                '01110',
                '00001',
                '00110',
                '00000',
                '00100'
                ];
                break;
        }
        if(!arrLetterCode) {
            var arrLetterCode = [
            '1111',
            '1111',
            '1111',
            '1111',
            '1111'
            ];						
        }
        return arrLetterCode;
    };
 
    // ACTIVATE
    $('#doit').click(function(){jsTexty.Make('#letterBox');});
});
Share and Enjoy:
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Mixx
  • Google Bookmarks
  • LinkedIn
  • Live
  • MySpace
  • Reddit
  • StumbleUpon
Categories: CSS, Fun, JavaScript Tags:

Loading JavaScript Better :)

July 20th, 2010 No comments

After watching some very stimulating google tech talks on YouTube, I walked away with some new insight on how browsers load content. The following is a technique I picked up that allows for all included javascripts to load in parallel (instead of sequentially), and to prioritize the loading of your visible page content first.

The following code is placed before the closing body tag (and not in the head, as is traditionally done).

<script type="text/javascript"> 
	var DocumentHead = document.getElementsByTagName('head')[0];
 
	function jsOptimizedLoader(src) {
		var Script = document.createElement('script');
			Script.src = src;
			Script.type = 'text/javascript';
			DocumentHead.appendChild(Script);
	}
 
	jsOptimizedLoader('js/app/foo.js');
	jsOptimizedLoader('js/app/bar.js');
	jsOptimizedLoader('js/app/boo.js');
	jsOptimizedLoader('js/app/far.js');
</script>

Once your DOM has finished loading, all the scripts tags are added to the head via javascript. Allowing your page to display PRIOR to spending the time loading all of those scripts will win you usability points and ease of access points with your audience.

Share and Enjoy:
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Mixx
  • Google Bookmarks
  • LinkedIn
  • Live
  • MySpace
  • Reddit
  • StumbleUpon

IE6 / IE7 jQuery Fix: Anchor Image Clickable Area

September 25th, 2009 3 comments

IE6 and IE7 both experience a problem in which images inside of block elements inside of anchors lose their click ability. Here’s an example:

<a href="rss-icon.png">
	<span style="display:block; width:100px; height:100px;">
		<img src="someImage.png" />
	</span>
</a>

Every area of the link remains click-able except for the surface consumed by someImage.png. (Note, this problem will not show in IE8, or FF)

Here’s a very small jQuery plugin I wrote to fix this particular issue.

(function($){
	$.fn.fixClick = function() {
		return this.each(function(){
			$(this)
				.css({cursor:'pointer'})
				.click(function(){
					window.location.href = $(this).attr('href'); 
				});
		});
	}
})(jQuery);

Simply select your target element(s) and use this plugin to make the entire anchor click-able again. Here’s an example:

$(document).ready(function(){
   $('a').fixClick();
});
Share and Enjoy:
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Mixx
  • Google Bookmarks
  • LinkedIn
  • Live
  • MySpace
  • Reddit
  • StumbleUpon
Categories: JavaScript, Web Design Tags: , , , ,

Alternating Styles in jQuery (Plug-In)

July 16th, 2009 No comments

This is a little script that I wrote, that lets you easily alternate the style of repeating class elements, or w/e elements you want to select. This is particularly useful for lists, and the like.

function($){
$.fn.styleAlternation = function(aClass, bClass) {
    var i = 0;
    return this.each(function() {
        if (++i % 2 != 0 && aClass!='') {
            $(this).addClass(aClass);
        } else if(bClass!='') {
            $(this).addClass(bClass);
        }
    });
}(jQuery);

The usage is very simple. Here’s the JavaScript:

$("#awesomeTable tr").styleAlternation("cssClass1","cssClass2");

From there, all you need to do is create your CSS. Example:

.cssClass1 { background: #000; color: #444; }
.cssClass2 { background: #999; color: #333; }

Here’s a screenshot:
Alternation Demo

Share and Enjoy:
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Mixx
  • Google Bookmarks
  • LinkedIn
  • Live
  • MySpace
  • Reddit
  • StumbleUpon
Categories: JavaScript Tags: ,

AJAX Calendar Loader Using jQuery

July 15th, 2009 No comments

My good pal Austin needed help turning his static calendar into one that could change the month, using AJAX. The calendar itself was written in PHP. Here is the quick and easy solution I came up with for him, using jQuery:

$(document).ready(function() {
 
   // Create Date Object
   var jsDateObject = new Date();
 
   // Create Calendar Object ( Holds all your variables, etc )
   var jsCalendar = {};
       jsCalendar.currentMonth = jsDateObject.getMonth();
 
   // Controls the NEXT button
   $("#jsCalendarNext").click(function() {
      // Update Active Month
      jsCalendar.currentMonth++;
         if(jsCalendar.currentMonth>12) { jsCalendar.currentMonth=1; }
 
      // Get New Calendar
      ajaxUpdateCalendar();
   });
 
   // Controls the PREV button
   $("#jsCalendarPrev").click(function() {
      // Update Active Month
      jsCalendar.currentMonth--;
         if(jsCalendar.currentMonth<1) { jsCalendar.currentMonth=12; }
 
      // Get New Calendar
      ajaxUpdateCalendar();
   });
 
   // Use AJAX to update the Calendar
   function ajaxUpdateCalendar() {
      $.post(
         "phpCalendarLoader.php",
         { calendarMonth: jsCalendar.currentMonth },
         function(data) {
            $("#jsCalendarContainer").html(data);
         },
         "html"
      );
   }
 
});

From here, all Austin had to do was set his $month variable to $_POST['calendarMonth'];.

Share and Enjoy:
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Mixx
  • Google Bookmarks
  • LinkedIn
  • Live
  • MySpace
  • Reddit
  • StumbleUpon
Categories: JavaScript Tags: ,