Javascript / HTML5 - Canvas获取选定的对象尺寸

时间:2014-05-23 22:16:18

标签: javascript html5 canvas

我在画布上有一个图像。图像包含不同颜色的方块。我要点击一个正方形,得到正方形的尺寸。 (像素) 例如,单击带有黄色边框的红色方块并返回24 X 100 我见过这样的代码。我认为这是解决方案的一部分......但似乎无法使其发挥作用。

有什么想法吗?

var canvas = document.getElementById("canvas");
if (canvas.getContext) {
    var canvas = document.getElementById("canvas");
    if (canvas.getContext) {
        var ctx = canvas.getContext("2d");

        // Let's draw a green square 
        ctx.fillStyle = "rgb(0,127,0)";
        ctx.fillRect(10, 10, 20, 20);

        // We will now get two pixels, the first one filling inside the above square and the other outside the square 
        var Pixel = ctx.getImageData(29, 10, 2, 1);

        // Let's print out the colour values of the first pixel. Since we have set the colour of the 
        // square as rgb(0,127,0), that is what the alert should print out. Since we have not set 
        // any alpha value, Pixel.data[3] should be the defualt 255. 
        alert("Pixel 1: " + Pixel.data[0] + ", " + Pixel.data[1] + ", " + Pixel.data[2] + ", " + Pixel.data[3]);

        // Print out the second pixel, which is outside the square. 
        // since we have drawn nothing there yet, it will show the default values 0,0,0,0 (Transparent Black)
        alert("Pixel 2: " + Pixel.data[4] + ", " + Pixel.data[5] + ", " + Pixel.data[6] + ", " + Pixel.data[7]);

        // Let's get the width and height data from Pixel 
        alert("Pixels Width: " + Pixel.width);
        alert("Pixels Height: " + Pixel.height);
    }
}

1 个答案:

答案 0 :(得分:1)

您可以使用.getImageData,但有一种更简单的方法......

保存您在对象中绘制的每个方块的信息:

var green={x:10,y:10,width:20,height:20,color:"rgb(0,127,0)"};

将所有对象放在数组中:

var squares=[];

squares.push(green);

然后当用户点击时,枚举所有保存的方块并查看鼠标是否超过一个:

for(var i=0;i<squares.length;i++){
    var s=squares[i];
    if(mouseX>=s.x && mouseX<=s.x+s.width && mouseY>=s.y && mouseY<=s.y+s.height){
        alert("You clicked on a square with size: "+s.width+"x"+s.height);
    }
}

[根据提问者的评论添加(评论被提问者删除)]

发问者删除的评论:

  

如果我没有关于方块的信息怎么办?这些正方形来自一张照片?

假设画布包含彩色矩形,这里是如何计算包含指定x,y坐标的彩色矩形的宽度x高度:

function calcColorBounds(x,y){

    var data=ctx.getImageData(0,0,canvas.width,canvas.height).data;

    var n=i=(y*canvas.width+x)*4;
    var r=data[i];
    var g=data[i+1];
    var b=data[i+2];

    var minX=x;
    while(minX>=0 && data[i]==r && data[i+1]==g && data[i+2]==b){
        minX--;
        i=(y*canvas.width+minX)*4;
    }

    i=n;
    var maxX=x;
    while(maxX<=canvas.width && data[i]==r && data[i+1]==g && data[i+2]==b){
        maxX++;
        i=(y*canvas.width+maxX)*4;
    }

    i=n;
    var minY=y;
    while(minY>=0 && data[i]==r && data[i+1]==g && data[i+2]==b){
        minY--;
        i=(minY*canvas.width+x)*4;
    }

    i=n;
    var maxY=y;
    while(maxY<=canvas.height && data[i]==r && data[i+1]==g && data[i+2]==b){
        maxY++;
        i=(maxY*canvas.width+x)*4;
    }

    alert("size",maxX-minX-1,"x",maxY-minY-1);

}