I have a canvas with ID foobar. I've already drawn to it.
let canvas = document.getElementById("foobar");
I need to rotate this canvas 90°. Rotating #foobar with CSS doesn't work:
#foobar {
/* When I click somewhere on the canvas, it registers the position of the click
as what the position would be pre-rotation rather than post-rotation. */
transform: rotate(90deg);
}
In addition, rotating the context only works when an element has yet to be drawn, so this won't work either:
let context = canvas.getContext("2d");
context.rotate(90 * (Math.PI / 180));
When registering clicks, try to use event.offsetX and event.offsetY. These should line up properly with the canvas coordinates. For example:
<canvas>
</canvas>
<style>
canvas {
transform: rotate(90deg);
/* just so the canvas is visible */
border-color: black;
border-style: solid;
}
</style>
<script>
// when canvas is clicked, draw a dot
const canvas = document.querySelector('canvas');
const ctx = canvas.getContext('2d');
canvas.addEventListener('click', (e) => {
const x = e.offsetX;
const y = e.offsetY
ctx.beginPath();
ctx.arc(x, y, 10, 0, 2 * Math.PI);
ctx.fillStyle = 'red';
ctx.fill();
});
</script>