TileRotate/js/app.js

89 lines
2.4 KiB
JavaScript
Raw Permalink Normal View History

2023-05-09 03:10:35 +00:00
var angle_arr = [];
function closest(val){
2023-05-09 04:06:42 +00:00
var lessThan0 = val < 0;
var geNinety = Math.abs(val)>=90;
if(geNinety)
if(lessThan0) {
val += 90}
else
val -= 90
2023-05-09 03:10:35 +00:00
x= angle_arr.reduce(function(prev, cur) {
2023-05-09 04:06:42 +00:00
return Math.abs(cur.angle - Math.abs(val)) < Math.abs(prev.angle - Math.abs(val)) ? cur : prev;
2023-05-09 03:10:35 +00:00
});
2023-05-09 04:06:42 +00:00
var output = x.angle;
if(geNinety)
output = x.angle + 90
if(lessThan0)
output = 0 - output
return [output,x];
2023-05-09 03:10:35 +00:00
}
window.onload = function() {
fetch('js/angles.json').then((response)=>response.json()).then((json)=>angle_arr=json.angles);
var input = document.getElementById('fileUpload');
input.addEventListener('change', handleFiles);
rotation.addEventListener("input", (event) => {
2023-05-09 04:06:42 +00:00
var closestAngle = closest(parseInt(event.target.value));
event.target.value = closestAngle[0];
2023-05-09 03:10:35 +00:00
angle.textContent = event.target.value;
2023-05-09 04:06:42 +00:00
tileImg(closestAngle[0]);
2023-05-09 03:10:35 +00:00
})
canvas.width = 700;
canvas.height = 700;
}
var img = new Image;
function handleFiles(e) {
img.onload = tileImg;
img.src = URL.createObjectURL(e.target.files[0]);
}
function tileImg(a) {
var ctx = document.getElementById('canvas').getContext('2d');
var image = img;
// Set the angle in radians
const angleDeg = a; // Replace with your desired angle in degrees
const angle = angleDeg * Math.PI / 180;
// Create a temporary canvas
var tempCanvas = document.createElement ("canvas");
var tempCtx = tempCanvas.getContext ("2d");
// Calculate the diagonal length of the original canvas
var d = Math.sqrt (canvas.width * canvas.width + canvas.height * canvas.height);
// Set the temporary canvas dimensions to the diagonal length
tempCanvas.width = d;
tempCanvas.height = d;
// Create the pattern on the temporary context
var pattern = tempCtx.createPattern (image, "repeat");
// Set the fill style on the temporary context
tempCtx.fillStyle = pattern;
// Save the temporary context state
tempCtx.save ();
// Translate to the center of the temporary canvas
tempCtx.translate (d / 2, d / 2);
// Rotate by the angle
tempCtx.rotate (angle);
// Draw the rectangle with the pattern on the temporary context
tempCtx.fillRect (-d / 2, -d / 2, d, d);
// Restore the temporary context state
tempCtx.restore ();
// Draw the temporary canvas on the original canvas
ctx.drawImage (tempCanvas, - (d - canvas.width) / 2, - (d - canvas.height) / 2);
}