JSFiddle - React, Tailwind, and code Playground
by bnickel
HTML
<button onclick="addAllCells()">Load</button><br>
<canvas width="1294" height="624"></canvas> <img width="2048" height="2048" src="foobar">
CSS
canvas {
position: relative;
}
canvas, img {
border: 5px outset gray;
}
JavaScript
var CELL_SIZE = 16;
function getImageName(x, y) {
x -= 33;
y -= 14;
return (y >= 0 ? (y + 1) + 's' : -y + 'n') + (x >= 0 ? (x + 1) + 'e' : -x + 'w');
}
function getImageSource(x, y) {
return 'http://imgs.xkcd.com/clickdrag/' + getImageName(x, y) + '.png';
}
var canvas = document.querySelector('canvas');
var img = document.querySelector('img');
var context = canvas.getContext('2d');
function addCell(x, y) {
var image = new Image();
image.onload = function () {
context.drawImage(image, x * CELL_SIZE, y * CELL_SIZE, CELL_SIZE, CELL_SIZE);
};
image.onerror = function () {
context.save();
context.fillStyle = "#999";
context.fillRect(x * CELL_SIZE, y * CELL_SIZE, CELL_SIZE, CELL_SIZE);
context.restore();
}
image.src = getImageSource(x, y);
}
function addAllCells() {
for (var x = 0; x < 81; x += 1) {
for (var y = 0; y < 39; y += 1) {
addCell(x, y);
}
}
}
canvas.addEventListener('mousedown', function (event) {
var x = (event.layerX / CELL_SIZE) | 0;
var y = (event.layerY / CELL_SIZE) | 0;
img.src = getImageSource(x, y);
});