【发布时间】:2014-05-23 22:16:18
【问题描述】:
我在画布中有一张图片。图像包含不同颜色的正方形。我会点击一个正方形并获取正方形的尺寸。 (像素) 例如单击带有黄色边框的红色方块并返回 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);
}
}
【问题讨论】:
标签: javascript html canvas