-
-
Save ivkusto/a2b6ce10863521e0dbf3c90b91084ce2 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* | |
* @param {String} imageSrc - ссылка на картинку | |
* @returns {Promise} | |
*/ | |
function traceImage(imageSrc) { | |
return new Promise((resolve) => { | |
const image = new Image(); | |
image.onload = function () { | |
const canvas = document.createElement('canvas'); | |
canvas.width = image.width; | |
canvas.height = image.height; | |
const context = canvas.getContext('2d'); | |
context.drawImage(image, 0, 0); | |
const imageData = context.getImageData(0, 0, canvas.width, canvas.height); | |
const data = imageData.data; | |
let min = 0; | |
for (let i = 0; i < data.length; i++) { | |
if (data[i] !== 255) { | |
min = i; | |
break; | |
} | |
} | |
let max = 0; | |
for (let i = data.length - 1; i >= 0; i--) { | |
if (data[i] !== 255) { | |
max = i; | |
break; | |
} | |
} | |
min = Math.floor(min / 4); | |
max = Math.floor(max / 4); | |
minX = min % imageData.width; | |
minY = Math.floor(min / imageData.width); | |
maxX = max % imageData.width; | |
maxY = Math.floor(max / imageData.width); | |
const rgb = getAt(minX, minY, imageData).join(', '); | |
resolve( | |
`<div><div style=" | |
position: absolute; | |
width: ${maxX - minX + 1}px; | |
height: ${maxY - minY + 1}px; | |
top: ${minY}px; | |
left: ${minX}px; | |
background-color: rgb(${rgb});"></div> | |
</div>`) | |
}; | |
image.src = imageSrc; | |
}); | |
function getAt(x, y, imageData) { | |
const index = (y * imageData.width + x) * 4; | |
return [imageData.data[index], imageData.data[index + 1], imageData.data[index + 2]]; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment