任何人都可以向我解释为什么这段代码会产生错误?
$("#crop-canvas-draw").on("click tap", function(e){
var pageX = device == 'touch' ? e.originalEvent.touches[0].pageX:e.pageX;
var pageY = device == 'touch' ? e.originalEvent.touches[0].pageY:e.pageY;
var x = pageX - $("#crop-canvas-primary").offset().left;
var y = pageY - $("#crop-canvas-primary").offset().top;
var replaceColor = 0;
/*
* scan
* - top
* - bottom
* - left
* - right
* */
var scan = function(x, y){
var imgData = ctxDraw.getImageData(x, y, 1, 1);
var data = imgData.data; // data is one dimension array
if(data[0] == 0 && data[1] == 0 && data[2] == 0){
data[0] = 0;
data[1] = 0;
data[2] = 255;
data[3] = 255;
ctxDraw.putImageData(imgData, x, y);
// re-scan
scan((x-1), y);
scan((x+2), y);
scan(x, (y-1));
scan(x, (y+2));
}else{
return;
}
}
scan(x, y);
});
我正在尝试在我的画布应用程序中创建油漆桶,我不知道它为什么会产生错误。
更新脚本,以便在远离左侧/顶部/右侧/底部时进行调节。
$("#crop-canvas-draw").on("click tap", function(e){
var pageX = device == 'touch' ? e.originalEvent.touches[0].pageX:e.pageX;
var pageY = device == 'touch' ? e.originalEvent.touches[0].pageY:e.pageY;
var x = pageX - $("#crop-canvas-primary").offset().left;
var y = pageY - $("#crop-canvas-primary").offset().top;
var replaceColor = 0;
/*
* scan
* - top
* - bottom
* - left
* - right
* */
var scan = function(x, y){
var imgData = ctxDraw.getImageData(x, y, 1, 1);
var data = imgData.data; // data is one dimension array
if(data[0] == 0 && data[1] == 0 && data[2] == 0){
data[0] = 0;
data[1] = 0;
data[2] = 255;
data[3] = 255;
ctxDraw.putImageData(imgData, x, y);
// re-scan
if((y == 0 || y == cvsDraw.height) && (x == 0 || x == cvsDraw.width)) return;
scan((x-1), y);
scan((x+2), y);
scan(x, (y-1));
scan(x, (y+2));
}else{
return;
}
}
scan(x, y);
});
答案 0 :(得分:0)
我猜这应该是你停止递归的方法:
if(data[0] == 0 && data[1] == 0 && data[2] == 0){
不幸的是,当您在越界像素上调用getImageData时,它会返回透明黑色(请参阅规范here)。您可以将您的条件更新为:
if(data[0] == 0 && data[1] == 0 && data[2] == 0 &&
x >= 0 && y >= 0 && x <= cvsDraw.width && y <= cvsDraw.height){
这应该确保你不会超出范围。
注意:更新解决方案失败的原因
if((y == 0 || y == cvsDraw.height) && (x == 0 || x == cvsDraw.width)) return;
是因为您正在检查边框上是否完全。但是,您有时会以2为增量移动坐标,这意味着您可以跳过确切的边缘。