Creating a Checkerboard Plane using Three.js

I am currently working on a Three.js project for a webpage 3D example where I want to create a checkerboard. The issue I am facing is that my code assigns three colors, but I only need two colors (black and white). How can I adjust the mathematical calculations to generate the correct checkerboard pattern?

// Creating geometry for the checkerboard
var cbgeometry = new THREE.PlaneGeometry( 500, 500, 8, 8 );

// Defining materials for the board
var cbmaterials = []; 

cbmaterials.push( new THREE.MeshBasicMaterial( { color: 0xffffff, side: THREE.DoubleSide }) );
cbmaterials.push( new THREE.MeshBasicMaterial( { color: 0x000000, side: THREE.DoubleSide }) );
cbmaterials.push( new THREE.MeshBasicMaterial( { color: 0x0000ff, side: THREE.DoubleSide }) );

// Assigning material based on the color index
var l = cbgeometry.faces.length / 2;

for( var i = 0; i < l; i ++ ) {
    var j = 2 * i;
    cbgeometry.faces[ j ].materialIndex = i % 3;
    cbgeometry.faces[ j + 1 ].materialIndex = i % 3;
}

// Creating the mesh with the defined materials
var cb = new THREE.Mesh( cbgeometry, new THREE.MeshFaceMaterial( cbmaterials ) );
scene.add( cb );

Answer №1

UPDATE:

If our development environments differ, I propose the following code correction:

UPDATE-2:

Instead of 'j's in the index selection part, use 'i's as shown below.

Give this a try:

// Geometry
var cbgeometry = new THREE.PlaneGeometry( 500, 500, 8, 8 );

// Materials
var cbmaterials = []; 

cbmaterials.push( new THREE.MeshBasicMaterial( { color: 0xffffff, side: THREE.DoubleSide }) );
cbmaterials.push( new THREE.MeshBasicMaterial( { color: 0x000000, side: THREE.DoubleSide }) );

var l = cbgeometry.faces.length / 2; // <-- This should remain 8x8 (64)

console.log("This should be 64: " + l);// Double-check if this is 64

for( var i = 0; i < l; i ++ ) {
    j = i * 2; // <-- Reintroduced to handle every other 'face'
    cbgeometry.faces[ j ].materialIndex = ((i + Math.floor(i/8)) % 2); // Replace all 'i's with 'j's here. KEEP THE 8
    cbgeometry.faces[ j + 1 ].materialIndex = ((i + Math.floor(i/8)) % 2); // Include this line too for the other half of each face
}

// Mesh
cb = new THREE.Mesh( cbgeometry, new THREE.MeshFaceMaterial( cbmaterials ) );
scene.add( cb );

The changes made are documented within the code.

I introduced Math.floor(i/8) into the material index to alternate layers. Without it, only vertical lines would appear.

Furthermore, I eliminated the 3rd material, leaving only white and black options.

Thank you for posing this question; it was enjoyable to work through!

Answer №2

How about using a THREE.ShaderMaterial() for this effect?

Your vertex shader could look something like this,

varying vec2 vUv;
void main(){
vUv = uv;
gl_FragPosition = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
}

For the fragment shader, you can try something similar to this code snippet:

varying vec2 vUv;
void main(){
vec2 tileUV = vec2(500.0, 500.0);// For repeating the texture 500 times in both directions
vec2 repeatedUV = vUv * tileUV ;
repeatedUV -=floor(repeatedUV);

The repeatedUV variable now contains tiled textures within the 0-1 range that repeat.

repeatedUV.x = floor(repeatedUV.x * 2.0);// This will create black or white stripes in the U direction
repeatedUV.y = floor(repeatedUV.y * 2.0);// Same for the other direction

This process is akin to boolean algebra with textures.

float finalMask = repeatedUV.x + repeatedUV.y;// Bottom left: 0, bottom right: 1, top left: 1, top right: 2
finalMask *= 1.0 - repeatedUV.x*repeatedUV.y; // All zeroes except for the top right
gl_FragColor = vec4(vec3(finalMask), 1.0);

}

This may not be the most efficient way, but it avoids creating thousands of triangles. It's a procedurally generated solution.

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

Background of jQuery-UI Slider

Can the background color of a jQuery-UI Slider widget be set using JavaScript? This is the default setting: What I am trying to accomplish is the following: The green range should be determined based on historical data. I want to visually show the user ...

Error message encountered in React Material-UI while attempting to run the basic Hello World test - Invalid hook call

My plan is to kick off a project using React and Material-UI. I decided to start with the simplest Hello World example based on the official documentation, in a brand new Ubuntu OS. However, when I tried running the code, an error popped up! Here's wh ...

What is the best way to trigger a new css animation on an element that is already in the midst of

Let's talk about an element that already has an animation set to trigger at a specific time: .element { width: 100%; height: 87.5%; background: #DDD; position: absolute; top: 12.5%; left: 0%; -webkit-animation: load 0.5s ease-out 5s bac ...

JQuery for personalized path animations

After developing an android app that sends onTouchEvents points to a web server, I've been able to retrieve motion points JSON data using Ajax. Here is a snippet of the data: {"data":[ {"x":224.28035,"y":235.4906}, {"x":263.32916,"y":219.45718}, {"x" ...

Updating HTML content with Node JS using MYSQL data

Seeking Guidance on Updating HTML Data Using Node.js I am looking for a way to update the HTML data in my files using Node.js without the use of EJS or any view engine. My views folder contains .js files that return HTML, and I need to change the data fro ...

Discovering the method to access query parameters in a node.js module

Creating a straightforward pagination module for an express app is essential. Here's an example of the code I have implemented: var config = require('../config'); function Pagination(options) { this.param = options.param || 'page ...

Is it possible to maintain the data types of each individual piece of data when it's divided into an array in

Can the data type of each field be preserved in Javascript after splitting it using the split method? Input: var row = "128, 'FirstName, LastName', null, true, false, null, 'CityName'"; When using the split method, the data type of e ...

Troubleshooting issue with error handling in graphql mutation hook with react and apollo is not resolving

It seems like I might have overlooked a configuration in my code, but I can't seem to pinpoint where I went wrong. In our application, we have a basic login form. If the correct username and password are entered, everything works smoothly. However, ...

There seems to be an issue with posting JSON data correctly

Currently, I am attempting to include an object with numerous attributes within it. This is the object I am trying to use with $.post: ({"fname" : fname, "lname" : lname, "gender" : gender, "traits" : { "iq" : inte ...

What's the most effective method for updating the title of the date header on MUI Date Picker?

Does anyone know how to customize the title of the Calendar in MUI Date Picker? I want to add a specific string to the display that shows the month and year, like "August 2014." https://i.stack.imgur.com/qgMun.png I've searched the API but couldn&ap ...

Are you harnessing the power of Ant Design's carousel next and previous pane methods with Typescript?

Currently, I have integrated Ant Design into my application as the design framework. One of the components it offers is the Carousel, which provides two methods for switching panes within the carousel. If you are interested in utilizing this feature using ...

Trigger Object RuntimeError

Initially, I attempted to pass the object :id to the URL and it was successful. However, when I tried to pass the object to the list, I encountered a ReferenceError. index.ejs: <tr> <th class="text-center">AWB NO</th> <th c ...

Automatically fill in input fields in a form by selecting options from a dropdown menu and extracting data

After executing a MySQL query, a select dropdown menu is populated with data like this: <form method="post" action="action.php"> <select name="elements" id="elements"> <option type="text" value="">Select an element to be modifie ...

Unable to modify text or utilize any of the buttons within CKEDITOR

My goal is to have a div that, when clicked, will trigger the opening of CKEDITOR. The contents of the div should then be loaded into the editor. When I click outside of the editor, I want the contents of the editor to be displayed back in the div. Below ...

Difficulty with NodeJS, Hapi, and Cascading Style Sheets

I've decided to challenge myself by creating a small webhost using Node.js with hapi. Even though I'm not an expert in Node.js, I am eager to learn as much as possible. Currently, my main issue revolves around fetching a CSS file from an include ...

Replicate and customize identical object for creating instances in JavaScript

I am working with an object that has the following structure: var customObject = function() { this.property = "value"; }; customObject.prototype = new otherObject(); customObject.prototype.property2 = function() {}; This is just a snippet as the ac ...

The ng-model does not reflect changes when using the JQuery datepicker

Currently, I have set up two textboxes for users to choose a date. I am utilizing JqQuery's datepicker UI to showcase a small calendar pop-up whenever the user clicks on the textbox. However, an issue arises when I select a date in the calendar popup ...

An element featuring a background color is vertically aligned in the middle of its parent container

Struggling to achieve a seemingly simple task, but coming up short on finding a solution. The goal is to have a background-color that aligns vertically in the middle of the first and last images in a stack of images. It may sound more complicated than it a ...

What is the reason for Firefox displaying the "excessive recursion" error message?

I have been working on generating an area Google chart using the code below, but I am running into an issue where Firefox is showing me a "too much recursion" error. The chart currently only has one point for testing purposes. Can anyone provide some gui ...

What steps are necessary to instruct multer to store the file in a specific directory?

Having some issues with multer while trying to save an image in a specific folder. The path for the file gets uploaded to mlab successfully, but the problem arises when attempting to retrieve the image from the designated folder as it fails to save there ...