Skip to content

Instantly share code, notes, and snippets.

@drofp
Created October 18, 2020 22:47
Show Gist options
  • Save drofp/c327ec11f168457fd4042b93ba9a658c to your computer and use it in GitHub Desktop.
Save drofp/c327ec11f168457fd4042b93ba9a658c to your computer and use it in GitHub Desktop.
show pixels values where mouse is hovering: https://yangcha.github.io/ImageViewer/
<!DOCTYPE HTML>
<!-- Display image, show mouse position and pixel values
Author: Changjiang Yang
Date: 08/14/2016
TODO: Add drag and drop
source: https://yangcha.github.io/ImageViewer/
-->
<html>
<head>
<style>
div.footer {
position: fixed;
bottom: 0;
left: 0;
margin: 0 auto;
background: #0072BB;
color:#fff;
}
</style>
</head>
<body>
<p>Open image: <input type="file" id="inputImage"/></p>
<canvas id="canvas" style="margin:12px;"></canvas>
<div class="footer" id="results">Move mouse over image to show mouse location and pixel value and alpha</div>
<script>
var URL = window.URL;
var cvs = document.getElementById('canvas');
var ctx = cvs.getContext('2d');
var res = document.getElementById('results');
cvs.addEventListener('mousemove', mousePos, false);
window.onload = function() {
var inputImage = document.getElementById('inputImage');
inputImage.addEventListener('change', handleImageFiles, false);
}
function mousePos(evt) {
var rect = cvs.getBoundingClientRect();
var x = parseInt(evt.clientX - rect.left);
var y = parseInt(evt.clientY - rect.top);
var p = ctx.getImageData(x, y, 1, 1).data;
results.innerHTML = '<table style="width:100%;table-layout:fixed"><td>X: '
+ x + '</td><td>Y: ' + y + '</td><td>Red: '
+ p[0] + '</td><td>Green: ' + p[1] + '</td><td>Blue: '
+ p[2] + '</td><td>Alpha: ' + p[3]+"</td></table>";
return {x, y};
}
function handleImageFiles(e) {
var url = URL.createObjectURL(e.target.files[0]);
var img = new Image();
img.onload = function() {
cvs.width = img.width;
cvs.height = img.height;
ctx.drawImage(img, 0, 0);
}
img.src = url;
}
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment