26
Feb/08
0

Quick Tip, “Firebug breakpoints not breaking!”

When using FireBug to step through your JavaScript code in FireFox, sometimes it does not break on a line that you know is being executed. If you are like me you are like WTF, what is going on? I eventually realized that the reason FireBug was not breaking on some lines of my code was that the code I set my breakpoint on was inline and not inside a function. Apparently FireBug will not break on a line that is not inside a function. A quick fix for this is to wrap your code in a function and call the function immediately after declaring the function.

Instead of:

1
2
var foo = "stuff";
alert(foo);

Use:

1
2
3
4
5
function showFoo(){
    var foo = "stuff";
    alert(foo);
}
showFoo();

In the second block you can put breakpoints on either line inside the function showFoo() and FireBug will break when you expect it to.

For more on debugging JavaScript in Firefox check my Firebug post or my article on conditional break points.

[Post to Twitter]  [Post to Plurk]  [Post to Yahoo Buzz]  [Post to Delicious]  [Post to Digg]  [Post to Ping.fm]  [Post to Reddit]  [Post to StumbleUpon] 

5
Dec/07
0

Using setTimeout in objects with Mootools

Often you wish to use setTimeout to call a function in the objects you are creating with MooTools or perhaps even more often you would like to pass parameters into your set time out calls. Well, the MooTools framework has given us a plethora of tools to do all of this and more. In this post I will discuss how you can pass parameters with setTimeout (Well, not really ‘into’ setTimeout, but a better way to get the same result.) and call your functions, delayed and recurring, from your objects created with the MooTools class function.

Closures and bind()

The first problem we tend to encounter the first time we try to do this is that when our member function gets called by setTimeout we get a bunch of errors that our variables are undefined. This problem is caused by JavaScript’s lack of closures which means that there is not hard binding between the function and the object that it is declared in. If you do a little debugging you will discover that the this operator is pointing at the window object not your object. The reason for that is that setTimeout causes the function to be called by the window object and in JavaScript this points to the calling scope.

Because the issue of closures is a problem in many cases when using JavaScript MooTools came up with a generic solution to the problem called bind. The bind() method is a part of the functions.js, found in the Native collection of MooTools functions. Their docs on bind can be found here. The Bind() member function will allow you to bind the this operator to any object you choose, which often will be the this of the object you define it in, but could be any object in the DOM. You can use bind when you call set time out like setTimeout(this.myfunction.bind(this), 1000) to call functions in your object delayed and have still have the this operator point at what you expect it to. That having been said, MooTools has two other functions to help you with delayed and recurring function calls in a much more efficient manner.

Delayed and Recurring calls

As this is an article about setTimeout, you are most likely unconcerned with what closures are and are just wanting your delayed function or recurring/polling/periodic function to work. If so, this is the section for you! The MooTools library provides two functions for calling functions, either delayed or periodically. They are, not surprisingly, called ‘delay’ and ‘periodical’. You use delay when you want a function to execute in so many seconds or periodical when you want a function to execute every so many seconds. Both of these functions return their timer ID and can be stopped by passing that into the $clear() function.

Delay example:

delay_demo = new Class({

    initialize: function(dateString){

        this.count = 0;

        this.delayTimer = this.updateCount.delay(1000, this);

    },

    updateCount: function(){

        this.count++;

    }

});

periodical example:

periodical_demo = new Class({

    initialize: function(dateString){

        this.count = 0;

        this.startTimer();

    },

    updateCount: function(){

        this.count++;

    },

    stopTimer: function(){

        $clear(this.periodicalTimer);

    },

    startTimer: function(){

        this.periodicalTimer = this.updateCount.periodical(1000, this);

    }

});

Passing Parameters

Another important feature of bind, delay and periodical is that they will allow you to pass parameters or arguments to the functions they call. Passing arguments to a function called with bind, delay or periodical is as easy as adding a second parameter for bind and, in the case of delay and periodical, a third parameter that is an array of parameter values; e.g., myfunction.periodical(1000, this, [ParamVal1, ParamVal2, "strParamVal3"]) or myfunction.bind(this, [ParamVal1, ParamVal2, "strParamVal3"]).

Common Errors Encountered

There are some situations where you might get an error that does not really explain what the problem is. I have run into two when working with these functions. The first is the “too much recursion” error from Firefox or FireBug. This error indicates that you have used the parenthesis in a place you should not have, an example is using myfunction().delay(1000, this) instead of myfunction.delay(1000, this). The other is having a function that calls periodical that calls its self, which will cause an exponential increase in the number of calls to that function until your browser locks up.

periodical lockup example:

periodical_demo = new Class({
    initialize: function(dateString){
        this.count = 0;
        this.startTimer();
    },
    updateCount: function(){
        this.count++;
    },
    stopTimer: function(){
        $clear(this.periodicalTimer);
    },
    startTimer: function(){
        this.periodicalTimer = this.startTimer.periodical(1000, this); //Note calling startTimer from inside startTimer with periodical is very bad.
    }
});

MooTools has neatly provided simple ways to accomplish all of the tasks we would normally use setTimeout for.

[Post to Twitter]  [Post to Plurk]  [Post to Yahoo Buzz]  [Post to Delicious]  [Post to Digg]  [Post to Ping.fm]  [Post to Reddit]  [Post to StumbleUpon] 

19
Apr/07
0

Debugging using Conditional breakpoints with Firefox and Firebug.

Some times you have an error inside a loop that can be a real pain to get to. You certainly don’t want to put a breakpoint inside a loop and hit F10 a few thousand times until you get to the error condition. In this article, I would like to talk about a few tools in Firebug for Firefox to make debugging in these situations much easier and faster. Note, if you are not familiar with debugging, you may want to read my previous Firebug article

First, there is Continue. Continue is the function that will tell the debugger to continue executing the script until it encounters another breakpoint. In Firebug, Continue is the blue arrow pointing to the right in the upper right of Firebug. You can also use the F8 key to continue. You can use continue inside a loop to skip to your breakpoint in the next iteration of the loop.

Perhaps the most important tool for debuging inside of loops is the conditional breakpoint. You can set a condition on a breakpoint so it will only break when a specified condition is true. Giving the following code (open debug loops example):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
1: <SCRIPT LANGUAGE="JavaScript">
2:
3: function init(){
4:  var myArray = new Array(99);
5:
6:  for(i = 0; i<99; i++){
7:      myArray[i] = i*2;
8:  }
9:
10:     myBody = document.getElementsByTagName("body").item(0);
11:     for(i = 0; i<=99; i++){
12:         myBody.innerHTML += myArray[i];
13:         myBody.innerHTML += "<br />";
14:     }
15: }
16:
17: </SCRIPT>
18: <BODY onload="init();">
19:
20: </BODY>
21: </HTML>

I could put a breakpoint on line 12, but I would have to hit F8 (Continue) 99 times to get to the end of the loop, which can get tiresome. Something much less tiresome and much more efficient is to attach a condition to the breakpoint. A condition can be added to a breakpoint by right clicking on it. Right clicking on a break point will bring up a pop up that will allow you to enter a condition for the breakpoint. In the case of the code above I am going to use ‘i=99′, so my code execution will break when the variable ‘i’ is equal to 99.

By using conditional breakpoints you can easily conquer errors in your loops, find those pesky random values that break everything, and save time getting to the core of the issue.


[Post to Twitter]  [Post to Plurk]  [Post to Yahoo Buzz]  [Post to Delicious]  [Post to Digg]  [Post to Ping.fm]  [Post to Reddit]  [Post to StumbleUpon] 

15
Apr/07
4

Debugging JavaScript in Firefox with Firebug

In this article I would like to cover some of the basics of using Firebug to debug JavaScript in Firefox. If you do not have Firefox or the latest version I suggest you download Firefox, install it then get the Firebug extension. There is simply no better solution for debugging JavaScript than Firefox and Firebug at least not from what I have seen.

If you want to debug JavaScript in Internet Explorer check out this post: Debug JavaScript in Internet Explorer

Firebug provides many features that help you write better code for your web sites from Inspecting HTML to debugging scripts. The latter being one of the most important additions to the web application programming arsenal to come along in a long time, especially in this day and age of web 2.0 and AJAX. If you are familiar with another IDE such as Visual Studio, debugging in Firebug will be very familiar. All of the tools you are used to, well all of the important ones anyway, are there.

If you have just installed Firebug it is likely disabled by default. Click on the Tools menu in Firefox then the Firebug menu and finally if Disable Firebug has a check next to it, click it to remove the check. Alternately, you can press F12 then click the Enable Firebug link.

So for this article we need just a simple html file with some JavaScript in order to go over the basics. Following is a block of html you can use or you can download the html file here.


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
    <title>Debug Example</title>
	<script language="javascript" type="text/javascript">
		function init(){
			var myDiv = document.createElement("div");
			var bodyNode = document.getElementsByTagName("body").item(0);;
			myDiv.style.backgroundColor = "#aaffaa";
			myDiv.style.width = "100px";
			myDiv.style.height = "100px";
			var divText = document.createTextNode("Hello World!");
			myDiv.appendChild(divText);
			bodyNode.appendChild(myDiv);
		}

	</script>
</head>
<body onload="init();">

</body>
</html>

Once you have the debug_example_script.html on your system, open it in Firefox. It should load with no errors and have the text “Hello World” in a green box. Now that the page is open, look on the right hand side of the Firefox status bar, you should see a green circle with a check mark in it. Click that circle to open Firebug. Firebug will open as a frame in your browser and, along the top of that frame, there will be a set of menu items/tabs, starting with Console. The fourth option should be Script. Click the Script tab to open the script debugger.

Now that you have the script debugger open you should see the code from the page on the left and the Watch pane on the right. The first thing we are going to do is set a break point so we can step into the code and inspect its variables and objects. To set a Break Point, click the gray area next to the line number on which you want the code to break. In this case we want to click the gray area to the left of line number 7.

Now that we have a break point set, we want to reload the page so that our code will execute. Hit the refresh button or F5 to reload the page. You will notice that the green box does not appear on the page, and that in the left pane of the Firebug frame there is a yellow arrow on our break point. This means that the execution of the script has paused on that line so we can inspect things. In the Watch pane you will see a few items that Firebug has automatically added for us. For now you can ignore those.

Now that we are actively debugging you can mouse over variables and objects in the code to see to what value they are set. Since we have stopped on the first line of our init() function most everything is undefined as we have not actually executed any of the code. To execute the current line of code and move to the next line (step over) you can press the yellow arrow that points down on the top right of Firebug or, press the F10 key.

After pressing the F10 key you will notice that the yellow arrow next to the line numbers has moved down to line 8. Now if you hover your mouse over myDiv you will get a popup that says “div”. So line 7 has executed and created a new div element and assigned it to the myDiv variable. If you look over in the Watch pane in Firebug you will notice that myDiv says “div” and has a plus sign next to it. Go ahead and click the plus sign, this will open a tree view of the myDiv object so you can inspect all of its members.

Ok, so lets make use of stepping through code to solve a problem. First, after line 14, add the following lines to your JavaScript:


	var aNum1 = "55a";
	var aNum2 = 10;
	var ar = aNum1 * aNum2;
	alert(ar);

We are going to pretend that we do not know why our alert keeps displaying NaN. So we are going to put a break point on line 14 and step through the code. Click the break point next to line 7 to remove it and click next to line 14 to add a break point there, then hit F5 (reload the page.) Next we press F10 to step over line 15 and 16 and stop when the yellow arrow is on line 17. Now we can look at aNum1 and aNum2 in the Watch pane, and it is easy to see that aNum1 is a string and aNum2 is a number.

That should give you a basic introduction to the Firebug debugger and how it can help you develop JavaScript more efficiently. There is a lot more that Firebug can do for you so make sure to explore the tool thouroughly.

[Post to Twitter]  [Post to Plurk]  [Post to Yahoo Buzz]  [Post to Delicious]  [Post to Digg]  [Post to Ping.fm]  [Post to Reddit]  [Post to StumbleUpon] 

11
Apr/07
1

The correct way to work with table elements in FireFox, IE and all other browsers

In my last post I talked about the differences between IE and Firefox when creating dynamic tables with the Document Object Model. Thanks to chatdor’s comment to my “Dynamic Tables In JavaScript for IE and Firefox” post, I realized that I was not paying attention to the full DOM. Perhaps many of us, like me, tend to only think of the Element object when thinking about manipulating the DOM, but there are a couple of higher level objects that derive from the Element object, the Table Element, and the Form Element, that make dealing with the more complex Elements easier. The good folks over at Mozilla have a great DOM reference which I almost always have open.

So, all that being said, I would like to post some code on a better way of creating dynamic tables in JavaScript with the DOM. In the following block of code we will use createElement(‘table’), to create our table but from then on we will use the Table Element’s member function insertRow and the Row’s insertCell to build the table.

1
2
3
4
5
var myTable = document.createElement('table');
var myRow = myTable.insertRow(-1);
var myCell = myRow.insertCell(-1);
var myTextNode = document.createTextNode('Hello World!');
myCell.appendChild(myTextNode);

In this block, I pass -1 into the insert functions to append the row or cell to the end of the rows or cells. Also in the example instead of setting the cell’s innerHTML or useing createElement(“text”) to make a text node and append, I instead use document.createTextNode, which is another case where there is a DOM function that is likely better to use than the less specific functions.

By using the higher level Table object and calling functions more specific to an action the code should have better cross-browser functionality.

[Post to Twitter]  [Post to Plurk]  [Post to Yahoo Buzz]  [Post to Delicious]  [Post to Digg]  [Post to Ping.fm]  [Post to Reddit]  [Post to StumbleUpon] 

8
Apr/07
2

Dynamic Tables In JavaScript for IE and Firefox

Edit : After reading chatdor’s comment I realized that I was consentrating so much on the Element that I was not seeing the whole DOM. See my new post on the DOM, for a better sample for creating table elements in JavaScript.


Recently I had the “pleasure” of dynamic creating some tables in JavaScript. In the process, I ran into and interesting issue or two. The first issue is that you cannot just append <tr> elements into a <table> element in IE. It will work, but IE will not render the rows. In IE you must create a <tbody> element, append the <tbody> element to the <table> element, then append your rows to your <tbody> element. This does not follow the W3C Row groups specification for the table specification which states that: “Table rows may be grouped into a table head, table foot, and one or more table body sections, using the THEAD, TFOOT and TBODY elements, respectively.” Note that the W3C specification states ‘may be’ whereas IE treats it as “must be.”

So, the following will get you nothing in IE but will work fine in Firefox:

1
2
3
4
5
6
var myTable = document.createElement("table");
var myRow = document.createElement("tr");
var myCell = document.createElement("td");
myCell.innerHTML = "Hello World!";
myTable.appendChild(myRow);
myRow .appendChild(myCell);

This will render a table in both IE and Firefox:

1
2
3
4
5
6
7
8
var myTable = document.createElement("table");
var myTbody = document.createElement("tbody");
var myRow = document.createElement("tr");
var myCell = document.createElement("td");
myCell.innerHTML = "Hello World!";
myTable.appendChild(myTbody);
myTbody.appendChild(myRow);
myRow.appendChild(myCell);

So now we have a table that renders in both IE and Firefox but there is still an issue remaining. Now in Firefox there is a space between the top of the table and the first row that you cannot get rid of. This is not going to be evident in all situations but will be in enough situations to be a problem. The reason for the space is that when you add a <tbody> to a table in Firefox it appears to reserve or auto include the <thead> and <tfoot> elements in the table. This is most likely done because the W3C specification states that you must have a <thead> and <tfoot> if you have a <tbody>. In order to prevent this extra space you need to add the<thead> and the <tfoot> and set their height to 0px or their display to none or something of the sort unless, of course, you are going to use them.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
var myTable = document.createElement("table");
var myThead = document.createElement("thead");
myThead.style.height = 0px;
var myTfoot = document.createElement("tfoot");
myTfoot.style.height = 0px;
var myTbody = document.createElement("tbody");
var myRow = document.createElement("tr");
var myCell = document.createElement("td");
myCell.innerHTML = "Hello World!";
myTable.appendChild(myThead);
myTable.appendChild(myTfoot);
myTable.appendChild(myTbody);
myTbody.appendChild(myRow);
myRow.appendChild(myCell);

This gives you a way to render tables that match in both IE and Firefox with the same code.

[Post to Twitter]  [Post to Plurk]  [Post to Yahoo Buzz]  [Post to Delicious]  [Post to Digg]  [Post to Ping.fm]  [Post to Reddit]  [Post to StumbleUpon] 

8
Apr/07
0

Color Picker version 1.0.2 released

I have made a couple of small updates to the JavaScript Color Picker and the Color Picker project page today.

I fixed a bug with IE and dynamically created tables using the DOM method. Fixed a few layout issues I came across and added the showColorInfo Option. I also updated the example pages so they are integrated into the site and layout a little better.

Enjoy!

-=Kelly

[Post to Twitter]  [Post to Plurk]  [Post to Yahoo Buzz]  [Post to Delicious]  [Post to Digg]  [Post to Ping.fm]  [Post to Reddit]  [Post to StumbleUpon] 

2
Apr/07
2

Color Picker v1.0.1 Released

I have done some debugging of the color picker in Opera. There were problems with many of the Canvas functions needed in Opera 9.0, but things work beautifully in Opera 9.1.

I have also done some testing with Firefox 1.5 and Safari. Things do not work at all well in FireFox 1.5 as it is missing some key functionality and I am not planning on making it work in old versions of FireFox given 2.0’s wide spread install base.

Safari is close to working but I am having specific problems with the context.createLinearGradient() function in my version of Safari. Even though; when I look at the context it says that the createLinearGradient function exists it keeps returning undefined for me when I call it. If there are any Mac/Safari gurus out there that can see why this might be happening I would love to hear from you.

The Color Picker now supports FireFox 2.0, IE 7.0, and Opera 9.10.

See examples and download from the Color Picker Project Page.

[Post to Twitter]  [Post to Plurk]  [Post to Yahoo Buzz]  [Post to Delicious]  [Post to Digg]  [Post to Ping.fm]  [Post to Reddit]  [Post to StumbleUpon] 

1
Apr/07
0

Complete JavaScript Color Picker

Welcome to the final installation of my JavaScript based Color Picker series. I have made a lot of changes to the color picker since my last installment.

Layout
I found some major problems based on the document type with the way I was laying out elements in the color picker dialog, so I decided that it needed to use the lowest common denominator in order to work reliably, so it is laid out with, *gasp* tables.

Sizing
After adding the support for the Canvas element I decided to add options to size the HueBar and the SV Box.

1
2
3
4
5
6
7
8
9
10
    if(this.Options.hueBarWidth){
        this.HueBar.setStyle("width", this.Options.hueBarWidth);
    }else{
        this.HueBar.setStyle("width", "30");
    }
    if(this.Options.hueBarHeight){
        this.HueBar.setStyle("height", this.Options.hueBarHeight);
    }else{
        this.HueBar.setStyle("height", "360");
    }

Options
I added the ability to pass in an Options object that gives the ability to customize many parts of the Color Picker.

1
2
3
4
    this.Options = {};
    if(objOptions){
        this.Options = objOptions;
    }

Open/Close
I created Open and Close member functions on the color picker object its self.

1
2
3
4
5
6
    open: function (){
        this.Container.setStyle("display", "block");
    },
    close: function (){
        this.Container.setStyle("display", "none");
    }

You can download the full source from the JavaScript Color Picker project page.

[Post to Twitter]  [Post to Plurk]  [Post to Yahoo Buzz]  [Post to Delicious]  [Post to Digg]  [Post to Ping.fm]  [Post to Reddit]  [Post to StumbleUpon] 

25
Mar/07
1

Enhancing the JavaScript Color Picker with the Canvas element

With the previous implementation of the Color Picker I used div elements to make the individual “pixels” of the color picker, attaching an event to each div element. This incurs quite a bit of overhead, causing the color picker to perform poorly especially on slower systems. The most obvious way to create something like a color picker efficiently is to use the Canvas element.

First, I needed to detect whether the browser supports the Canvas element. I do that by creating a Canvas element and then seeing if it will return a context like so:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
testcanvas = document.createElement("canvas");

if(testcanvas.getContext){

 this.supportsCanvas = true;

 delete testelement;

}else{

 this.supportsCanvas = false;

 delete testelement;

}

Next, in the constructor I needed to create Canvas elements instead of div containers for the Hue Bar and SV Box. Here is a snip of code for the Hue bar:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
if(this.supportsCanvas){

 //create the canvas Saturation Value Box.

 this.HueBar = new Element("canvas");

 this.HueBar.setStyle("cssFloat", "left");

 this.HueBar.setStyle("styleFloat", "left");

 this.HueBar.setStyle("margin-right", "5px");

 this.HueBar.width=30;

 this.HueBar.height=360;

 this.HueBar.addEvent("click", this.setCurrentHue.bind(this));

 this.Container.appendChild(this.HueBar);

}else{

 //create the container for the hue bar.

 this.HueBar = new Element("div");

 this.HueBar.setStyle("width", "30px");

 this.HueBar.setStyle("cssFloat", "left");

 this.HueBar.setStyle("styleFloat", "left");

 this.HueBar.setStyle("margin-right", "5px");

 this.Container.appendChild(this.HueBar);

}

Note: in the case of using the Canvas element, the events are attached to the canvas instead of child elements.

The next difference is in the drawHueBar and drawSVBox functions. In the drawHueBar function, we figure out the multiplier we will need for get steps between 0 and 360 for the height of our bar. Create a new color that is at hue 0 and full saturation and brightness. Get a 2d context to the HueBar canvas element. Iterate over the height of the HueBar. Set the hue for the current position on the HueBar. Get the Hex color string for the new Hue. Set the Canvas Context’s fill style to the Hex color string. Then, fill a Rect that is as wide as the HueBar and 1 pixel tall with that color. Rinse and repeat until we have iterated the whole HueBar.

Here is a snip of code from the drawHueBar function:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
drawHueBar: function (){

 if(this.supportsCanvas){

    hSteps = 360 / this.HueBar.height;

    hColor = new Color([0,100,100], 'hsb');

    myCTX = this.HueBar.getContext('2d');

    strhHex = "";

    for(hi =  this.HueBar.height; hi &gt; 0; hi--){

        hColor.changeHue(hi*hSteps);

        strhHex = hColor.rgbToHex();

        myCTX.fillStyle = strhHex;

        myCTX.fillRect(0, this.HueBar.height-hi, this.HueBar.width, 1);

    }

 }else{

    hsvColor = new Color([0,100,100], 'hsb');

    fcoDiv = new Element("div");

    fcoDiv.setStyle("width","30px");

    fcoDiv.setStyle("height","1px");

    ...

 }

}

For the SVBox, it is mostly the same, changing the Brightness in the loop instead of the Hue. I make use of the Canvas element’s gradient fill functions to simplify the work. Inside the loop over the height of the SVBox, we create a new gradient that goes from the left side of the SVBox to the Right. We add a color stop to the linear Gradient that is just a gray value between white and black based on the current position in the height of the SVBox. Then we add a color stop that is based on the current iterations HSV value. Set the Canvas context’s fill style to the gradient and then fill one row of the SVBox.

myLinearGrad = myCTX.createLinearGradient(0, 0, this.SVBox.width, 0);
myLinearGrad.addColorStop(0, "rgb("+vi+","+vi+","+vi+")");
myLinearGrad.addColorStop(1, strsvHex);
myCTX.fillStyle = myLinearGrad;

In the case of using the Canvas element, the UpdateSVBox code does the exact same thing as the drawSVBox.

Getting the color clicked on is a little different and we need to deal with the DOM a little more. In order to get the color clicked on we need to call the getImageData(X, Y) function from a Canvas context object. The issue with that is the event.ClientX and the event.ClientY that is passed in is in the window coordinate space, not our canvas elements coordinate space, so we have to translate. In the event call back functions we need to do the following to get the colors from the Canvas elements. Get a 2d context to the Canvas element. Call the MooTools Element.getCoordinates() function to get the left and top of the canvas in the Window coordinate space. Then, for each axis subtract the Canvases left or top from the clientX or clientY then add the window.scrollX or window.scrollY to deal with the page being scrolled if it is. Pass the resulting X and Y into the context’s getImageData function to get an imageData object for the pixel. The imageData.data array will contain the RGB values for the pixel.

myCTX = this.HueBar.getContext('2d');
hBoxCoords = this.HueBar.getCoordinates();
myImageData = myCTX.getImageData(e.clientX - hBoxCoords.left + window.scrollX, e.clientY - hBoxCoords.top + window.scrollY, 1, 1);
CurHueColor = new Color([myImageData.data[0], myImageData.data[1], myImageData.data[2]]);

With this update the Color Picker is significantly faster with a capital ‘S’, unless you are using IE and then it is just as slow as before. (A fact which totally burns my britches, since IE has such a large portion of the browser market share. I will have to figure out something to do about that in the IE case.)

See the code for the whole Canvas enhanced ColorPicker class

Canvas based Color Picker example

This code was tested in IE 7 and Firefox 2. The Canvas element was not added to Firefox until version 2, no Canvas element in IE.

[Post to Twitter]  [Post to Plurk]  [Post to Yahoo Buzz]  [Post to Delicious]  [Post to Digg]  [Post to Ping.fm]  [Post to Reddit]  [Post to StumbleUpon] 

Tweet This Post links powered by Tweet This v1.3.9, a WordPress plugin for Twitter.