gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 12:33:13 25 4
gpt4 key购买 nike

我在 Canvas 上有一张图像。该图像包含不同颜色的方 block 。我要单击一个正方形并获取该正方形的尺寸。 (像素)例如,单击带有黄色边框的红色方 block 并返回 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);
}
}

最佳答案

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

保存有关您在对象中绘制的每个正方形的信息:

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

将所有对象放入数组中:

var squares=[];

squares.push(green);

然后当用户点击时,枚举所有保存的方 block 并查看鼠标是否位于一个上方:

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);
}
}

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

提问者删除的评论:

What if I don't have info on the squares. The squares are from a photo?

假设 Canvas 包含彩色矩形,以下是如何计算包含指定 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);

}

关于Javascript/HTML5 - Canvas 获取选定对象的尺寸,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23839067/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com