Implementing flat shading using Phong material alongside a focused spotlight

I'm attempting to achieve flat shading using the Phong material in Three.js. According to the documentation, I need to set flatShading:true in the configuration when creating the material. I've successfully created a cube with these settings and positioned a spot light to focus on the center of the cube (not touching the vertices).

I expected the faces of the cube to look the same at all pixels, but I'm seeing a reflection of light at the center of the face. Changing flatShading from true to false doesn't seem to impact the lighting.

Here is the JSFiddle link demonstrating what I've tried: https://jsfiddle.net/dj03gktb/.

Below is the code snippet:

var camera, scene, renderer;

init();
animate();

function init() {

  camera = new THREE.PerspectiveCamera(70, window.innerWidth / window.innerHeight, 0.01, 10);
  camera.position.z = 4;
  scene.add(camera);

  scene = new THREE.Scene();

  var ambientLight = new THREE.AmbientLight(0xcccccc, 0.2);
  scene.add(ambientLight);

  var pointLight = new THREE.SpotLight({ color: 0xffffff, angle: Math.PI / 10, intensity: 2 });

  scene.add(pointLight);
  
  pointLight.position.z = 1.5;
  pointLight.position.y = 0;

  var geometry = new THREE.BoxGeometry(1, 1, 1);
  
  var material = new THREE.MeshPhongMaterial({ color: 0xff0000, flatShading: true, shininess: 100, specular: 0x00ff00 });

  var mesh = new THREE.Mesh(geometry, material);
  scene.add(mesh);

  renderer = new THREE.WebGLRenderer({ antialias: true });
  renderer.setSize(window.innerWidth, window.innerHeight);
  document.body.appendChild(renderer.domElement);
}
function animate() {
  requestAnimationFrame(animate);
  renderer.render(scene, camera);
}

I may have misunderstood flat shading, or there could be a bug in Three.js or an issue with the rendering engine. Any assistance would be greatly appreciated.

Answer №1

Regrettably, opting to use a cube as an illustration of flat shading isn't the best choice because the difference won't be noticeable. Instead, try using a sphere:

var camera, scene, renderer;

init();
animate();

function init() {

    camera = new THREE.PerspectiveCamera( 70, window.innerWidth / window.innerHeight, 0.01, 10 );
    camera.position.z = 4;

    scene = new THREE.Scene();
        
    var ambientLight = new THREE.AmbientLight( 0xcccccc, 0.2 );
    scene.add( ambientLight );
        
    var spotLight = new THREE.SpotLight({ color: 0xffffff, angle: Math.PI / 10, intensity: 2});
    spotLight.position.z = 1.5;
    scene.add(spotLight);

    var geometry = new THREE.SphereBufferGeometry( 1, 12, 16);
    var material = new THREE.MeshPhongMaterial({color: 0xff0000, flatShading: true, shininess: 100, specular: 0x00ff00});

    var mesh = new THREE.Mesh( geometry, material );
    scene.add( mesh );

    renderer = new THREE.WebGLRenderer( { antialias: true } );
    renderer.setSize( window.innerWidth, window.innerHeight );
    document.body.appendChild( renderer.domElement );

}

function animate() {

    requestAnimationFrame( animate );
    renderer.render( scene, camera );

}
body {
  margin: 0;
}
canvas {
  display: block;
}
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d6a2bea4b3b396e6f8e7e7eef8e5">[email protected]</a>/build/three.js"></script>

It seems like the cube face should appear the same across all pixels, but this isn't the case.

Flat shading doesn't aim to achieve this. Typically, vertex normals are interpolated in the fragment shader, resulting in smooth rendering. Flat shading, on the other hand, ensures that the normals of a face are consistent throughout its flat surface. Therefore, there is no interpolation of vertex normals, but lighting calculations remain unaffected. As a result, specular highlights can still be observed.

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

Guide to taking a screenshot of an HTML page using Javascript, Jquery, and HTML5 functionality

I am looking to add a unique feature to my website - the ability to capture the current image of my webpage with just the click of a button. Inspired by Google's "send feedback" function, I want to implement something similar on my own site. After res ...

Having trouble getting event modifiers to work in Vue when added programmatically

Trying to dynamically add events using v-on through passing an object with event names as keys and handlers as values. It appears that this method does not support or recognize event modifiers such as: v-on=“{‘keydown.enter.prevent’: handler}” T ...

What is the most effective approach for managing two distinct ajax calls within a Laravel application?

I am working on a page with two separate ajax calls (using Laravel). The first call triggers the second one, but the options for the second ajax are in a select box. Here is my current solution: public function getCategoryAjax(Request $request) { $pr ...

Call upon the prototype method of the parent class

"I'm having trouble understanding a piece of my code: //constructor function Widget (options) { }; //return the string Widget.prototype._addEditFormString = function (val) { return "<in ...

Error encountered: Unexpected identifier in Reactjs code

I created a new application using create-react-app and encountered an Uncaught SyntaxError: Unexpected identifier for this particular line: import React, { Component } from 'react'; within the file public/scripts/app.js: 'use strict' ...

AngularJS simplifies request handling by allowing currying of requests

I am working with three forms within the same container, each triggered by a specific objectId. I want to create a function that can handle all actions related to these objectIds. Unfortunately, I am restricted to using ES5. var applyActions = function( ...

Executing jQuery post request on a div loaded via ajax

I'm facing a challenge with my webpage. I have a section where the content of a div is loaded via ajax. This div contains forms, and after submission, it should update to display the new content without refreshing the entire page. Can anyone guide me ...

Ensuring the server application is up and running before initiating the mocha tests

This is similar to Ensuring Express App is running before each Mocha Test , but the proposed solution isn't effective + I am utilizing a websocket server In essence, I'm making use of a websocket framework called socketcluster and this represent ...

Tips for extracting parameters from a URL using Express JS in a custom manner

Recently, I set up a server using the express package and encountered an issue while trying to extract parameters from the URL in a specific format. The URL structure is as follows: (notice there's no '?' indicating parameters). I am lookin ...

It is not possible to make a call to Response.Redirect from within a static method

Hello, I am attempting to execute a webmethod using ajax from an aspx page. Essentially, I would like to redirect to another aspx page with a query string, but I need to do it through <a href> because it is part of a jQuery menu. Based on my underst ...

Property '{}' is not defined in type - Angular version 9.1.1

Currently, I am working with Angular CLI version 9.1.1 and I am attempting to update certain data without updating all of it. form: UserInfo = {adresse : {}}; UserInfo.interface export interface UserInfo { id_user: string; username: string; em ...

In Vue2, you can utilize $ref to retrieve information from a child component and transfer it into the parent component's data

Trying to access child components' data in Vue2 and move it into the parent component's data without triggering an event. Saving count:20 from the child component into the parent component in the example below. Please let me know if there are any ...

Angular integrated with DOJO application

I'm currently working on incorporating Angular into an existing DOJO application. I've set up a plunkr http://plnkr.co/edit/8pgdNwxFoxrDAQaQ4qfm?p=preview, but unfortunately, the angular module is not loading. Can anyone provide guidance on what ...

Uploading video files using XMLHttpRequest encountered an error on a particular Android device

One of our testers encountered an issue where they failed to upload a video file (.mp4) on a specific Android mobile phone. Interestingly, the same file uploaded successfully on an iPhone and another Android device. To investigate further, I attempted to ...

An array filled with unique and non-repeating elements

I want to display random country flags next to each other, making sure they do not match. However, my specific case requires a unique solution for dealing with arrays: function displayRandomFlags() { var flagurls = ["ZPlo8tpmp/chi","cJBo8tpk6/sov","QyLo ...

Encountering a 404 error indicating that the file cannot be found while attempting to log into an authentication system developed using express and node

Currently, I am in the process of developing a demonstration banking application that facilitates user sign up and sign in functionality using express.js and node.js. The API created accepts POST requests to /signup and /authenticate routes successfully wh ...

Why is "undefined" being used to alert an ajax call response?

I am encountering an issue with a returned value from an AJAX request. The web method being referenced returns a boolean value of true or false. However, when attempting to access this value outside the AJAX method, I am receiving an "undefined" message :? ...

Retrieving data from MySQL using PHP and AJAX with radio button selection

How can I update my code to display data from the database when a radio button is clicked instead of using a drop-down box? Here is an example of my current radio button code: <Input type='Radio' Name='compcase' value='1'/& ...

Fluid Grid design showcasing a gap on the right side

After working on the Skeleton Framework and making adjustments to the grid design, I am facing a small gap issue on the right side. Despite things slowly falling into place, this minor gap is causing confusion. Please refer to the image below for clarifica ...

Leveraging Angular 2 and RxJs 5 beta observables to continuously stream data from a while loop

I am looking to develop a straightforward Angular 2 application that calculates prime numbers within a while loop and continuously updates the view with newly discovered values. My goal is to showcase the list of prime numbers using *ngFor in real-time, gi ...