2

I have an object of pixel map, each row contains an object of columns, that contains a colour information. Then I choose the colour using switch(), and then I simply draw it to canvas. Here is the code:

  for(var pixX in pixmap) {
    for(var pixY in pixmap[pixX]) {
      switch(pixmap[pixX][pixY]) {
        case 1: var pixColor='lightgray'; break;
        case 2: var pixColor='black'; break;
        default: var pixColor='forestgreen'; break;
        }
      $('canvas#surface').drawRect({
        fillStyle: pixColor,
        width: 1, height: 1,
        x: pixX, y: pixY,
        fromCenter: false
        });
      }
    }

It draws the pixels, but the pixel position is somehow zoomed, although, the pixels are really just 1px big. I can't determine, how much it zooms. When I draw after a while to the canvas, the position is correct. What's the problem?

Edit: I've recreated it on jsFiddle: http://jsfiddle.net/qyNTn/

Aslanex
  • 79
  • 2
  • 9
  • Recreate in jsFiddle, so that we can understand better the problem – Givi Apr 06 '13 at 16:33
  • What are you trying to do? i don't understand, in your fiddle you just create 6 dots size of 2px – Givi Apr 06 '13 at 18:44
  • Maybe you ought to read jCanvas API docs... http://calebevans.me/projects/jcanvas/docs/ – Givi Apr 06 '13 at 18:50
  • In real code the pixel map comes via ajax from mysql, but the problem is same - the dot position is zoomed. – Aslanex Apr 07 '13 at 17:50

1 Answers1

1

Simply put, the pixX and pixY variables are converted to strings by JavaScript. You need to convert pixX and pixY to numbers before passing them to jCanvas.

The reason being is because JavaScript stores each key name (for any object) as a string. Therefore, when you iterate through an object using a for in loop, the key name will always be a string. In other words, pixX and pixY are treated as strings, so you need to convert them to numbers using a function such as parseFloat.

In addition, jCanvas performs many numerical calculations when drawing shapes, so it always prefers a number over a string for any numerical value.

Anyway, fixing your code (to produce the expected behavior) only requires a single change to your drawRect() parameters.

x: parseFloat(pixX), y: parseFloat(pixY),
caleb531
  • 4,111
  • 6
  • 31
  • 41