방법은 다음과 같습니다
- 는 픽셀 데이터 배열을 가져
- 한 번에 한 행씩 픽셀을 이동하십시오.
- 행에서 가장 긴 연속 수평선을 계산하십시오.
- 계산 된 행이 maxLine보다 길면 해당 긴 행을 maxLine으로 설정하십시오.
- 모든 행을 완료하면 가장 긴 연속 수평선을 얻게됩니다.
이 각 행을 스캔하고 맥스 라인을 계산하는 코드는 여기에
// set up variables to hold the results
var maxLength=0;
var maxY;
var maxStartX;
var maxEndX;
// step through each horizontal line
for(var y = 0; y < canvas.height; y++) {
var continuous=0;
for(var x = 0; x < canvas.width; x++) {
if(data[((canvas.width * y) + x) * 4 + 3]>0){
// calculate this line's maximum continuouse line
continuous++;
}else{
// if this line's line is longer than maxLength
if(continuous>maxLength){
// replace maxLength with this line's data
maxLength=continuous;
maxY=y+1;
maxEndX=x-1;
maxStartX=maxEndX-continuous+1;
}
continuous=0;
}
}
}
코드와 바이올린입니다 : 우리는 당신의 코드 referrence이있는 경우 http://jsfiddle.net/m1erickson/nvd49/
<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" media="all" href="css/reset.css" /> <!-- reset css -->
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<style>
body{ background-color: ivory; padding:20px; }
#canvas{border:1px solid red;}
</style>
<script>
$(function(){
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
ctx.beginPath();
ctx.moveTo(20,20);
ctx.lineTo(20,220);
ctx.lineTo(80,220);
ctx.closePath();
ctx.fill();
ctx.beginPath();
ctx.moveTo(100,100);
ctx.lineTo(65,125);
ctx.lineTo(100,150);
ctx.lineTo(135,125);
ctx.closePath();
ctx.fill();
ctx.fillRect(175,0,30,canvas.height);
// get the pixel-data array
var imageData = ctx.getImageData(0,0,canvas.width,canvas.height);
var data = imageData.data;
// set up variables to hold the results
var maxLength=0;
var maxY;
var maxStartX;
var maxEndX;
// step through each horizontal line
for(var y = 0; y < canvas.height; y++) {
var continuous=0;
for(var x = 0; x < canvas.width; x++) {
if(data[((canvas.width * y) + x) * 4 + 3]>0){
// calculate this line's maximum continuouse line
continuous++;
}else{
// if this line's line is longer than maxLength
if(continuous>maxLength){
// replace maxLength with this line's data
maxLength=continuous;
maxY=y+1;
maxEndX=x-1;
maxStartX=maxEndX-continuous+1;
}
continuous=0;
}
}
}
ctx.beginPath();
ctx.moveTo(maxStartX,maxY);
ctx.lineTo(maxEndX,maxY);
ctx.strokeStyle="orange";
ctx.lineWidth=1;
ctx.stroke();
$("#results").text(maxLength+"px long from ["+maxStartX+"/"+maxY+"] to ["+maxEndX+"/"+maxY+"]");
}); // end $(function(){});
</script>
</head>
<body>
<p>The longest continuous horizontal line:</p>
<p>(Highlighted by the orange line)</p>
<p id="results"></p>
<canvas id="canvas" width=300 height=250></canvas>
</body>
</html>
, 그 것 큰!!! –
여기 있습니다. 그것은 매우 혼란 스럽다! –