sebastian
sebastian

Reputation: 159

How to get position of painted object in canvas

What i want to do is draw simple shape let's say rectangle by mouse and get directly from canvas his coordinates, height and width, it's possible?

I wrote this function:

function getImageProperties(image){
    var xMin = image.width;
    var xMax = 0;
    var yMin = image.height;
    var yMax = 0;
    var w = image.width, h = image.height;
     for (var y = 0; y < h; y ++) {
       for (var x = 0; x < w; x ++) {
           for (var c = 1; c < 5; c += 1) {
           var i = (x + y * w) + c;
           if(image.width* image.height * 4 != i){
                if(image.data[i] != 0){
                    if(x<xMin)
                        xMin = x;
                    if(x>xMax)
                        xMax = x;
                    if(y<yMin)
                        yMin = y;
                    if(y>yMax)
                        yMax = y;
                }
            }
         }
       }
     }
    var imgProp = {
        x : xMin,
        y : yMin,
        width: (xMax-xMin),
        height : (yMax-yMin)
    };
    return imgProp;
}

where

image = context.getImageData(0, 0, context.canvas.width, context.canvas.height);

but returned data is not same as i send to the drawning function :/

Upvotes: 1

Views: 1948

Answers (2)

Alnitak
Alnitak

Reputation: 339955

It looks like you're trying to find the rectangle enclosing all non-black pixels in the image data, but if so I can see a few minor issues, mostly with offset calculations. Try this:

function getImageProperties(image){
    var xMin = image.width - 1;
    var xMax = 0;
    var yMin = image.height - 1;
    var yMax = 0;
    var w = image.width, h = image.height;
     for (var y = 0; y < h; ++y) {
        for (var x = 0; x < w; ++x) {
           var i = 4 * (y * w + x);
           for (var c = 0; c < 4; ++c, ++i) {
              if (c != 3 && image.data[i]) { // ignore the alpha channel
                 xMin = Math.min(x, xMin);
                 xMax = Math.max(x, xMax);
                 yMin = Math.min(y, yMin);
                 yMax = Math.max(y, yMax);
              }
           }
        }
     }

     return {
        x : xMin,
        y : yMin,
        width: (xMax - xMin) + 1,
        height : (yMax - yMin) + 1
     };
 }

That said, if you just drew the rectangle with a mouse it would be far easier to simply record the last two pairs of coordinates used in your mouse event handlers!

Upvotes: 1

Jani Hartikainen
Jani Hartikainen

Reputation: 43253

You could try reading the pixel colors using getImageData, but it really isn't such a good idea.

The best approach would be to store the positions and other data in an array outside the canvas.

Upvotes: 0

Related Questions