Skip to content

Instantly share code, notes, and snippets.

@yossan
Created March 6, 2021 04:31
Show Gist options
  • Save yossan/6609b864a208c9214548aaf074421507 to your computer and use it in GitHub Desktop.
Save yossan/6609b864a208c9214548aaf074421507 to your computer and use it in GitHub Desktop.
A sample.html rotating rect at center in Canvas
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body style="min-height: 100% height: 100%">
<canvas id="drawingview" style="width: 100%; height: 100%">
<script>
let canvas = document.getElementById('drawingview')
let ctx = canvas.getContext('2d')
ctx.fillStyle = "red"
ctx.fillRect(0, 0, canvas.width, canvas.height)
let rect = { x: 10, y: 10, w: 30, h: 30 }
ctx.fillStyle = "green"
ctx.fillRect(rect.x, rect.y, rect.w, rect.h)
let theta = Math.PI / 4.0
drawRotatedBlueRect(ctx, rect, theta);
ctx.restore()
function drawRotatedBlueRect(ctx, rect, theta) {
let center = { x: rect.w / 2.0, y: rect.h / 2.0 }
// Anchor point
let ap = center
let rotatedAp = rotatePoint(ap, theta)
let dap = { x: ap.x - rotatedAp.x, y: ap.y - rotatedAp.y };
ctx.save()
ctx.translate(rect.x, rect.y);
ctx.translate(dap.x, dap.y)
ctx.rotate(theta)
ctx.fillStyle = "blue"
ctx.fillRect(0, 0, rect.w, rect.h)
ctx.restore()
}
function rotatePoint(point, theta) {
let x2 = point.x * Math.cos(theta) - point.y * Math.sin(theta)
let y2 = point.x * Math.sin(theta) + point.y * Math.cos(theta)
return { x: x2, y: y2 }
}
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment