Displaying grid in object in threejs: a tutorial

I currently have a horizontal grid Helper and polygon within my scene.

Is there a way to hide the grid outside of the polygon, similar to the image below?

https://i.sstatic.net/pQ40h.png

Here is the JSFiddle

var camera, scene, renderer, controls, geometry, material, mesh, gridHelper, polygon;
var edges = [{
  "x": -204.87113421108512,
  "y": -150,
  "z": 350.73338884671745
}, {
  "x": -204.87113421108535,
  "y": -150,
  "z": -38.02713383973953
}, {
  "x": -83.08211641046344,
  "y": -150,
  "z": -39.62530388610881
}, {
  "x": -78.88807649109879,
  "y": -150,
  "z": -538.3155247201529
}, {
  "x": 220.63777329601388,
  "y": -150,
  "z": -535.796479191672
}, {
  "x": 220.63777329601444,
  "y": -150,
  "z": 176.94968924487634
}, {
  "x": -53.07402331399715,
  "y": -150,
  "z": 176.9496892448766
}, {
  "x": -53.07402331399726,
  "y": -150,
  "z": 350.41591086077415
}];

init();
animate();

function init() {

  scene = new THREE.Scene();
  
  renderer = new THREE.WebGLRenderer({ alpha: true, antialias: true });
renderer.setPixelRatio(window.devicePixelRatio);
  renderer.setSize(window.innerWidth, window.innerHeight);
  renderer.setClearColor(0x555555, 1);
  renderer.sortObjects = true;
  
  document.body.appendChild(renderer.domElement);

  camera = new THREE.PerspectiveCamera(50, window.innerWidth / window.innerHeight, 1, 10000);
  scene.add(camera);
  
  camera.position.x =  1000;
 camera.position.y =  2000;
camera.position.z =  -1000;
  
controls = new THREE.OrbitControls( camera );


  gridHelper = new THREE.GridHelper(1500, 30);
  gridHelper.position.y = -150;
  scene.add(gridHelper);


  var shape = new THREE.Shape();
  let firstEdge = edges[0];
  shape.moveTo(firstEdge.x, -firstEdge.z);
  const len = edges.length;
  for (let i = 1; i < len; i++) {
    shape.lineTo(edges[i].x, -edges[i].z);
  }

  shape.lineTo(firstEdge.x, -firstEdge.z);
  
  var material = new THREE.MeshBasicMaterial({
      color:0x00aa00,
      opacity:0.5,
      side:THREE.DoubleSide,
      transparent:true,
      depthTest:false
    });

  var polygonGeometry = new THREE.ShapeGeometry(shape);
  polygon = new THREE.Mesh(polygonGeometry, material);
  polygon.position.y = firstEdge.y;
  polygon.rotation.x = -Math.PI / 2.;
  polygon.name = this.name;
  scene.add(polygon);

}

function animate() {
controls.update();
  window.requestAnimationFrame(animate);
  render();

}

function render() {

  renderer.render(scene, camera);

};
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/three.js/100/three.js"></script>
      <script type="text/javascript" src="https://threejs.org/examples/js/controls/OrbitControls.js"></script>

Any insights or suggestions on how to achieve this would be greatly appreciated!

Answer №1

The effect I was able to achieve using a stencil buffer can be seen at this link: https://jsfiddle.net/mmalex/g3hf4zxc/

https://i.sstatic.net/eH6Bm.png

const gl = renderer.getContext();
polygon.onBeforeRender = function () {
    gl.enable(gl.STENCIL_TEST)
    gl.stencilFunc(gl.ALWAYS, 1, 0xFF);
    gl.stencilMask(0xFF);
    gl.stencilOp(gl.KEEP, gl.KEEP, gl.INCR);
}
polygon.onAfterRender = function() {
    gl.disable(gl.DEPTH_TEST);
}
polygon.renderOrder = 999;

gridHelper.onBeforeRender = function() {
    gl.enable(gl.STENCIL_TEST)
    gl.stencilMask(0x00);
    gl.stencilFunc(gl.EQUAL, 1, 0xFF);
}
gridHelper.onAfterRender = function() {
    gl.disable(gl.STENCIL_TEST)
}
gridHelper.renderOrder = 1000

Unfortunately, achieving this effect required sacrificing mesh opacity, as three.js sorts opaque and transparent objects separately:

.renderOrder : Number This value allows the default rendering order of scene graph objects to be overridden although opaque and transparent objects remain sorted independently. Sorting is from lowest to highest renderOrder. Default value is 0.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

A sleek and streamlined scrollspy that dynamically updates the active class exclusively for anchor tags

Can anyone help me with this coding problem? I'm currently working on a minimalistic scrollspy code that adds an active class when the content is offset.top. The code works fine, but I want to change the active class to apply to the "a" tag instead of ...

Analog Clock Time Adjustment Bubble Deviation Dilemma

Recently, I encountered an issue with an analog clock component. Every time I click on the time adjustment bubble repeatedly while also moving the cursor position, it tends to drift away from its original placement, which should ideally be between an orang ...

Generate a dynamic file import loop within a React application

Suppose I have a directory containing several .md files: /static/blog/ example_title.md another_example.md three_examples.md and an array that includes all the titles: const blogEntries = ["example_title", "another_example", "three_examples"] In ...

What is the proper way to incorporate quotation marks within other quotation marks?

Is there a way to generate an ID within the myFunction() function in JavaScript? I need a single string to call an HTML script as a variable. Any corrections or suggestions are welcome. Here is a sample code snippet: <button class="tablinks" onclick=" ...

Access denied for generating login hint on target domain in javascript web application for Google sign-in

Utilizing the Google signin Javascript API with the gapi-signin-button on a webapp. The app is being served by a gulp server, binding to 0.0.0.0. Everything works fine during local development, but encountering issues when accessing the page through a publ ...

Issue with implementing jQuery tab functionality

I'm just starting to learn JS, HTML, and CSS, and I could use some guidance on setting up jQuery tabs. Currently, I'm encountering an error that says "Uncaught TypeError: $(...).tabs is not a function". Any help would be greatly appreciated. Than ...

I am experiencing difficulty with the color of my progress bar in Firefox

After successfully creating an interactive progress bar that works perfectly in Google Chrome and surprisingly also in Safari without vendor prefixes, I encountered a roadblock when testing it on Firefox. The progress bar color reverts back to the default ...

JavaScript can extract a portion of an array

Is it possible to generate a new array consisting of all elements ranging from the nth to the (n+k)th positions within an existing array? ...

The production deployment of Heroku using Nuxt is configured with staging environment variables

My deployment process involves using Heroku to deploy my Nuxt.js frontend app, where I have configured a variable for the API URL. However, whenever I move an app from staging to production, the production site ends up using the configuration variables fr ...

PrestaShop - Using ajax to update a JSON object with PUT request

I've been attempting to update a JSON object (such as a customer), but I keep encountering the following error: "NetworkError: 405 Method Not Allowed - ..." Here's my code (index.js): var testWebService = angular.module('testWebService& ...

The color of the background does not remain changed permanently

I'm having an issue where the background color changes when I click a button, but reverts back almost immediately to its original color. How can I ensure that the new color stays permanently? Here is a simple JavaScript function you can use: functio ...

Discover the CSS auto height value using JavaScript

Is there a way to utilize JavaScript in determining the value set for auto height in CSS? My development stack includes Grails and jQuery. For instance, consider the following CSS: .tool-preview { height: auto; } ...

Navigating the grid layout in Material UI can be tricky to

I'm struggling to grasp the concept of the grid system in material UI. Within my grid container, I have two grid items that I want to be centered and occupy the entire width. The button element appears centered, but the typography element does not. A ...

Stop Carousel when hovering over individual items (Owl Beta 2)

After creating a unique navigation that is separate from the carousel, I encountered some issues with the autoplay feature. Below is the HTML markup: <div class="carousel"> <div class=""> <img src="assets/img/carousel1.jpg" /&g ...

showcase every value upon submission in the form with options to edit and delete

Is it possible to display all values submitted in a form with edit and delete buttons? Currently, only one value is being displayed at a time. Whenever a new value is displayed, it replaces the old one. How can this be fixed? You can fin ...

Deactivate wheel event in jQuery

I am facing a challenge in designing my website using skrollr.js and fullpage.js libraries. Skrollr relies on the value of scrollTop to transform selected elements, while fullpage.js changes the top value of the viewport when scrolling, causing issues with ...

Vue Method always executed (regardless of click event)

I'm fairly new to vue and still getting a grasp on the fundamentals of my code. Currently, I am facing an issue with a Method. It should only trigger when the user clicks on the button, but it seems to be triggered all the time. I even tried adding ...

Utilizing objects from a JSON file within an HTML document

I'm currently in the process of creating a comprehensive to-do list, and I want to establish a JSON file that will link all the items on the list together. Despite my efforts, I find myself uncertain about the exact steps I need to take and the speci ...

My attempt at deploying my personal React App project on Vercel was unsuccessful

// encountering error during deployment on Vercel npm ERR! code ERESOLVE npm ERR! ERESOLVE could not resolve npm ERR! npm ERR! While resolving: @testing-library/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="e99b8c888a9da9d8da ...

Add an event listener to a specific class in order to control the visibility of its child elements by

Whenever I click on the "title text" link, the <ol> element refuses to hide, despite my efforts. After thoroughly reviewing the jQuery documentation and scouring Stack Overflow for answers related to .click(), .children(), .toggle(), and .hide(), I a ...