var img = new Image();
img.onload = getPoints;
img.crossOrigin = 'anonymous';
img.src = "https://dl.dropboxusercontent.com/s/lvgvekzkyqkypos/path.png";
function getPoints(){
// set our canvas
var canvas = document.createElement('canvas'),
ctx = canvas.getContext('2d');
canvas.width = this.width;
canvas.height = this.height;
// draw the image
ctx.drawImage(this,0,0);
// get the middle y line
var imageData = ctx.getImageData(0,Math.floor(this.height/2), this.width, 1);
var data = imageData.data;
// set an empty object that will store our points
var pts = {x1: null, y1: Math.floor(this.height/2), x2: null, y2:Math.floor(this.height/2)};
// define the first opacity value
var color = 0;
// iterate through the dataArray
for(var i=0; i<data.length; i+=4){
// since we'relooking only for non-transparent pixels, we can check only for the 4th value of each pixel
if(data[i+3]!==color){
// set our value to this new one
color = data[i+3];
if(!pts.x1)
pts.x1 = i/4;
else
pts.x2 = i/4;
}
}
snippet.log('start points : '+pts.x1+'|'+pts.y1);
snippet.log('end points : '+pts.x2+'|'+pts.y2);
ctx.fillStyle = 'red';
ctx.fillRect(pts.x1-5, pts.y1, 10, 10);
ctx.fillRect(pts.x2-5, pts.y2, 10, 10);
document.body.appendChild(canvas);
}
body{background-color: blue}
<!-- Provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
剛剛完成測試它。奇蹟般有效。然而,我仍然試圖理解你的代碼如何與透明的第四個值一起工作,爲什麼data [i + 3]並沒有遍歷每個數據。無論如何,謝謝你給我一個開始! – tipsywacky
ctx.getImageData()確實會返回一個imageData對象。在這個對象中,有一個名爲'data'的屬性,它是一個ArrayBuffer。此ArrayBuffer包含每個像素的每個紅色,綠色,藍色和alpha(透明)值。因此,在這段代碼中,我正在迭代4個數據(每個像素)並只查找alpha值('data [i + 3]')。如果我必須檢查像素是否真的是白色的,我會完成if [data [i] === data [i + 1] === data [i + 2] === data [i + 3] === 255)' – Kaiido
啊!疑難雜症!非常感謝!這很有趣,這是如何工作的。 – tipsywacky