【发布时间】:2014-10-20 07:58:14
【问题描述】:
这是孩子们可以用记号笔和方格纸尝试的东西。用瓷砖进行面积估计,这让我想到了这个问题:https://math.stackexchange.com/questions/978834/area-estimation-with-tiling
我在<canvas> 中写了一个简单的代码,它查看一个图块的左上角像素,如果颜色不是红色,它会将图块变成蓝色。
问题:如何改进 AI,使其仅丢弃红色少于 50% 的图块?我需要一个平均(颜色密度)函数来确定这一点吗?
这是我的fiddle 代码,带有黑色边框。实际面积为3750个单位。当然,如果我减小图块大小,它会更接近实际区域(阅读:微积分 - 对孩子来说太先进了)。
var sourceHeight = 90;
var sourceWidth = 300;
var pixelation = 10;
var tile_count = 0;
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.fillStyle = "red";
ctx.moveTo(50, 75);
ctx.lineTo(200, 75);
ctx.lineTo(100, 25);
ctx.lineTo(50, 75);
ctx.fill();
ctx.fillStyle = 'lightgreen';
ctx.rect(0, 0, sourceWidth, sourceHeight);
ctx.fill();
var imgData = ctx.getImageData(0, 15, sourceWidth, sourceHeight);
var data = imgData.data;
for (var y = 0; y < sourceHeight; y += pixelation) {
for (var x = 0; x < sourceWidth; x += pixelation) {
var red = data[((sourceWidth * y) + x) * 4];
var green = data[((sourceWidth * y) + x) * 4 + 1];
var blue = data[((sourceWidth * y) + x) * 4 + 2];
if (red > 200) {
red = 255;
blue = 0;
green = 0;
tile_count += 1;
} else {
red = 135;
green = 206;
blue = 235;
}
for (var n = 0; n < pixelation; n++) {
for (var m = 0; m < pixelation; m++) {
if (x + m < sourceWidth) {
data[((sourceWidth * (y + n)) + (x + m)) * 4] = red;
data[((sourceWidth * (y + n)) + (x + m)) * 4 + 1] = green;
data[((sourceWidth * (y + n)) + (x + m)) * 4 + 2] = blue;
}
}
}
}
}
ctx.putImageData(imgData, 0, 115);
ctx.fillStyle = "black";
ctx.font = "14px Georgia";
ctx.fillText("Tile Size: " + pixelation, 200, 140);
ctx.fillText("Total Tiles: " + tile_count, 200, 155);
<canvas id="myCanvas" width="300" height="200" style="border:1px solid #d3d3d3;"></canvas>
【问题讨论】:
标签: javascript algorithm math canvas