Created
August 27, 2023 17:46
-
-
Save joegaffey/d9d4daf73c8e153e0132d3a1cdb0d448 to your computer and use it in GitHub Desktop.
Translate Three.js rotation to canvas rotation coordinates
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Set up the Three.js scene | |
const scene = new THREE.Scene(); | |
const camera = new THREE.PerspectiveCamera(50, window.innerWidth / window.innerHeight, 1, 10000); | |
camera.position.z = camera.position.y = 500; | |
scene.add(camera); | |
const geometry = new THREE.CubeGeometry(200, 200, 200); | |
const material = new THREE.MeshNormalMaterial(); | |
mesh = new THREE.Mesh(geometry, material); | |
scene.add(mesh); | |
camera.lookAt(mesh.position); | |
const renderer = new THREE.WebGLRenderer(); | |
renderer.setSize(window.innerWidth / 2, window.innerHeight / 2); | |
document.body.appendChild(renderer.domElement); | |
// Create the canvas 2D render | |
const canvas2d = document.createElement('canvas'); | |
canvas2d.width = window.innerWidth / 2; | |
canvas2d.height = window.innerHeight / 2; | |
const ctx = canvas2d.getContext('2d'); | |
ctx.scale(0.5, 0.5); | |
let dir = -1; | |
document.body.appendChild(canvas2d); | |
addEventListener('keypress', e => { | |
if(e.keyCode === 46) // Period | |
dir = -1; | |
else if(e.keyCode === 44) // Comma | |
dir = 1; | |
}); | |
animate(); | |
function animate() { | |
requestAnimationFrame(animate); | |
render(); | |
} | |
function render() { | |
mesh.rotateY(0.02 * dir); | |
renderer.render(scene, camera); | |
const angle = getMeshRotation(mesh).y; | |
ctx.clearRect(0, 0, window.innerWidth, window.innerHeight); | |
fillRotatedRect(ctx, | |
window.innerWidth / 2 - mesh.geometry.parameters.width / 2, | |
window.innerHeight / 2 - mesh.geometry.parameters.height / 2, | |
mesh.geometry.parameters.width, | |
mesh.geometry.parameters.height, | |
angle); | |
} | |
function getMeshRotation(mesh) { | |
const rotation = new THREE.Vector3(0, 0 ,0); | |
rotation.y = mesh.rotation.y; | |
if(Math.abs(mesh.rotation.z) < Math.PI / 2) | |
rotation.y *= -1; | |
return rotation; | |
} | |
function fillRotatedRect(ctx, x, y, width, height, angle) { | |
ctx.save(); | |
ctx.translate(x + width / 2, y + height / 2); | |
ctx.rotate(angle); | |
ctx.fillRect(-width / 2, -height / 2, width, height); | |
ctx.restore(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment