Skip to content

Instantly share code, notes, and snippets.

@namgo
Created September 20, 2018 17:45
Show Gist options
  • Save namgo/a15f37cfea8de1c9c8ab300319488194 to your computer and use it in GitHub Desktop.
Save namgo/a15f37cfea8de1c9c8ab300319488194 to your computer and use it in GitHub Desktop.
Image Hiro, tracking a moving image by a dot on the image
<!DOCTYPE html>
<!-- massive problem with this approach is that the image needs to maintain its size for the canvas pixel-stuff to be picked up properly -->
<html>
<head>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<style>
.text {
position: absolute;
}
#myimage {
max-width: 100%;
}
body {
background: green;
}
.warptext {
perspective: 50em;
}
#bodytext {
background: tomato;
font-size: 10em;
height: 70vh;
transform: perspective(50em) rotateX(50deg);
}
</style>
</head>
<body>
<img id="hiro" src="hiro.png">
<img id="myimage" src="imagewithhiro3.png">
<div id="text0" class="text">hello world</div>
<div id="text1" class="text">world hello</div>
<div id="text2" class="text">henlo human</div>
<div class="warptext"><div id="bodytext">What is up?</div></div>
<script>
function arraysIdentical(a, b) {
// -1 we are ignoring alpha value because alpha value may change
var i = a.length - 1;
if (i != b.length - 1) return false;
while (i--) {
if (a[i] !== b[i]) return false;
}
return true;
};
let img = document.getElementById('myimage')
let canvas = document.createElement('canvas')
placeText = function() {
canvas.width = img.width
canvas.height = img.height
canvas.getContext('2d').drawImage(img, 0, 0, img.width, img.height);
let hiro = document.getElementById('hiro')
let hiro_canvas = document.createElement('canvas')
hiro_canvas.width = img.width
hiro_canvas.height = img.height
hiro_canvas.getContext('2d').drawImage(hiro, 0, 0, hiro.width, hiro.height)
let hiro_color = hiro_canvas.getContext('2d').getImageData(1, 1, 1, 1).data
let hc_arr = Array.from(hiro_color)
let pixels = canvas.getContext('2d').getImageData(0, 0, img.width, img.height).data
let j = 0
console.log('hi')
for (let i = 0; i < (img.height * img.width); i++) {
let r = pixels[i*4]
let g = pixels[i*4+1]
let b = pixels[i*4+2]
let a = pixels[i*4+3]
if (arraysIdentical([r, g, b, a], hc_arr)) {
var y = parseInt(i / img.width, 10);
var x = i - y * img.width;
console.log(i, img.height, img.width)
$('#text'+j).css('left', x).css('top', y)
j++
}
}
j = 0
}
$(window).on('resize', placeText())
/* for (let i = 0; i < canvas.width; i++) {
for (let j = 0; j < canvas.width; j++) {
if (hiro_canvas == canvas.getContext('2d').getImageData(i, j, 1, 1).data) {
console.log(i, j)
}
}
}*/
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment