JSFiddle - React, Tailwind, and code Playground
by tfoller
HTML
<canvas id="bg"></canvas>
<script async src="https://unpkg.com/[email protected]/dist/es-module-shims.js"></script>
<script type="importmap">
{
"imports": {
"three": "https://unpkg.com/[email protected]/build/three.module.js"
}
}
</script>
JavaScript
import * as THREE from 'three';
import {
DragControls
} from 'https://unpkg.com/[email protected]/examples/jsm/controls/DragControls.js';
const pointInPolygon = (pts, x, y) => {
const pointSide = (p0, p1, x, y) =>
(p1[0] - p0[0]) * (y - p0[1]) - (x - p0[0]) * (p1[1] - p0[1]); // >0 left, =0 on, <0 right
let wn = 0; // winding number
for (let i = 0; i < pts.length - 1; i++) {
const [p, pn] = [pts[i], pts[i + 1]];
const above = p[1] <= y;
if (above && pn[1] > y && pointSide(p, pn, x, y) > 0) wn++;
else if (!above && pn[1] <= y && pointSide(p, pn, x, y) < 0) wn--;
}
return wn == 0 ? false : true;
};
// INIT
const [w, h] = [window.innerWidth - 100, window.innerHeight - 100];
const canvas = document.getElementById('bg')
const scene = new THREE.Scene()
const camera = new THREE.PerspectiveCamera(75, w/h, 0.1, 1000)
const renderer = new THREE.WebGLRenderer({
antialias: true,
alpha: false,
canvas: canvas
})
renderer.setPixelRatio(window.devicePixelRatio)
renderer.setSize(w, h)
camera.position.z = 30
// CUBE
const cubeGeometry = new THREE.PlaneGeometry(20, 20);
const cubeMaterial = new THREE.MeshBasicMaterial({
color: 'green'
})
const cube = new THREE.Mesh(cubeGeometry, cubeMaterial)
scene.add(cube)
// TRIANGLE
const triangleShape = new THREE.Shape()
.lineTo(0, 10)
.lineTo(10, 0)
.lineTo(0, 0)
const triangleGeometry = new THREE.ShapeGeometry(triangleShape);
const triangleMaterial = new THREE.MeshBasicMaterial({
vertexColors: true,
})
const triangle = new THREE.Mesh(triangleGeometry, triangleMaterial)
scene.add(triangle);
const clr = [255,0,0, 255,0,0, 255,0,0];
triangleGeometry.setAttribute('color', new THREE.BufferAttribute(new Uint8Array(clr), 3, true));
const controls = new DragControls([triangle, cube], camera, canvas);
const render = () => { renderer.render(scene, camera) };
controls.addEventListener('dragend', function(event) {
const pt = [[0,0],[0,11],[11,0],[0,0]];
const pc =...