Photo Puzzle Maker
Choose a photo to turn it into a puzzle:
<!DOCTYPE html>
<html>
<head>
<title>Photo Puzzle Maker</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
body{
font-family: sans-serif;
text-align: center;
margin-top: 50px;
}
input[type="file"]{
display: none;
}
#puzzle{
display: inline-block;
border: 3px solid #333;
margin-top: 20px;
}
#loader{
display: none;
margin-top: 20px;
}
#msg{
font-size: 1.2em;
color: red;
margin-top: 20px;
}
</style>
</head>
<body>
<h1>Photo Puzzle Maker</h1>
<p>Choose a photo to turn it into a puzzle:</p>
<input type="file" id="fileInput">
<label for="fileInput">Select File</label>
<br>
<button onclick="makePuzzle()">Make Puzzle</button>
<div id="puzzle"></div>
<img id="loader" src="https://cdnjs.cloudflare.com/ajax/libs/galleriffic/2.0.1/css/loader.gif" alt="Loading...">
<p id="msg"></p>
<script>
function makePuzzle(){
var fileInput = document.getElementById('fileInput');
var puzzleContainer = document.getElementById('puzzle');
var loader = document.getElementById('loader');
var msg = document.getElementById('msg');
if(fileInput.files.length == 0){
msg.innerHTML = "Please select a file.";
return;
}
var file = fileInput.files[0];
if(!file.type.startsWith('image/')){
msg.innerHTML = "Please select an image file.";
return;
}
var img = document.createElement('img');
img.onload = function(){
var width = img.width;
var height = img.height;
var cropSize = Math.floor(Math.min(width, height) / 4);
var cols = Math.floor(width / cropSize);
var rows = Math.floor(height / cropSize);
puzzleContainer.style.width = width + 'px';
puzzleContainer.style.height = height + 'px';
puzzleContainer.innerHTML = '';
loader.style.display = 'inline-block';
for(var i=0; i<rows; i++){
for(var j=0; j<cols; j++){
var canvas = document.createElement('canvas');
canvas.width = cropSize;
canvas.height = cropSize;
var ctx = canvas.getContext('2d');
ctx.drawImage(img, j*cropSize, i*cropSize, cropSize, cropSize, 0, 0, cropSize, cropSize);
var puzzlePiece = document.createElement('div');
puzzlePiece.style.width = cropSize + 'px';
puzzlePiece.style.height = cropSize + 'px';
puzzlePiece.style.display = 'inline-block';
puzzlePiece.style.backgroundImage = 'url(' + canvas.toDataURL() + ')';
puzzlePiece.style.backgroundSize = width + 'px ' + height + 'px';
puzzlePiece.style.backgroundPositionX = '-' + j*cropSize + 'px';
puzzlePiece.style.backgroundPositionY = '-' + i*cropSize + 'px';
puzzleContainer.appendChild(puzzlePiece);
}
}
loader.style.display = 'none';
};
img.onerror = function(){
msg.innerHTML = "There was an error loading the image.";
loader.style.display = 'none';
};
img.src = URL.createObjectURL(file);
}
</script>
</body>
</html>