What is preventing me from viewing the curve on the browser when I run my code?

As a beginner in JavaScript, Three.js, and Computer Graphics, I have been assigned the task of drawing the Bezier Curve using the de-Casteljau Algorithm. I have written the following code, but it seems to not work properly when viewed in a browser. Can someone please help me identify the error? Thank you very much.

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>Task 1 - Computer Graphics</title>
        <style>
            body {margin: 0;}
            canvas {width: 100%; height: 100%;}
        </style>
    </head>
    <body>
        <script src="three.js"></script>
        <script>
            var scene = new THREE.Scene(); 
            var camera = new THREE.PerspectiveCamera(45, window.innerWidth/window.innerHeight, 1, 1000);
            camera.position.x = 0;
            camera.position.y = 0;
            camera.position.z = 20;
            camera.lookAt(new THREE.Vector3(0,0,0));

            var renderer = new THREE.WebGLRenderer();
            renderer.setSize(window.innerWidth, window.innerHeight);
            renderer.setClearColor(0xeeeeee);

            document.body.appendChild(renderer.domElement);

            var objects = [], plane;
            var points = new Array();
            points.push(new THREE.Vector3(1, 4, 0));
            points.push(new THREE.Vector3(2, 1, 0));
            points.push(new THREE.Vector3(5, 2, 0));
            points.push(new THREE.Vector3(6, 6, 0));

            for(var i=0; i < points.length; i++){
                var curvePointsGeo = new THREE.PlaneGeometry(0.5, 0.5, 1, 1);
                var pointsMesh = new THREE.Mesh(curvePointsGeo, new THREE.MeshBasicMaterial({color: 0x000000}));
                pointsMesh.position.x = points[i].x;
                pointsMesh.position.y = points[i].y;
                pointsMesh.position.z = points[i].z; 
                scene.add(pointsMesh);
                objects.push(pointsMesh);
            }

            var line;
            var tempPoints;
            var temp;

            animate();

            function animate(){
                casteljau();
                render();
            }

            function casteljau(){
                var curvePoints = new THREE.Geometry();
                for(var i= 0.0; i<=1.0; i+=0.02){
                    temp = getCasteljauPoint(i);
                    curvePoints.vertices.push(temp);
                }
                line = new THREE.Line(curvePoints, new THREE.LineBasicMateria({color: 0xff0000}));
                scene.add(line);
            }

            function getCasteljauPoint(t){
                tempPoints = [];
                var n = objects.length-1;
                for(var i=0; i<=n; i++){
                    var p = new THREE.Vector2(objects[i].position.x, objects[i].position.y);
                    tempPoints.push(p);
                }
                for(var j = 1; j<=n; j++){
                    for(var k = 0; m <= (n-j); k++){
                        tempPoints[k].x = t*tempPoints[k].x + (1-t)*tempPoints[(k+1)].x;
                        tempPoints[k].y = t*tempPoints[k].y + (1-t)*tempPoints[(k+1)].y;
                    }
                }
                return new THREE.Vector3(tempPoints[0].x, tempPoints[0].y, 0);
            }
        </script>
    </body>
</html>

Answer №1

There are a few mistakes that need correcting:

Located near the end, you have

for(var k = 0; m <= (n-j); k++){

You should replace m with k

THREE.LineBasicMateria

is missing the l

Add a render function like this:

function render() {
    renderer.render(scene, camera);
}

Make sure to always check the browser console for any errors.

By the way, to remove scrollbars, include display: block; in your canvas style.

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

Expanding a Node.js class to incorporate additional static class elements

I have a query where I believe that extending a class might be the solution, but I am not entirely sure. Here is the scenario... There is a class defined as follows: class Field { apiName; /** * Creates an instance of Field with the given par ...

Node's original file name

Is there a way to retrieve the original filename from a file that has an absolute path in node.js? In node.js, I can use path.basename to get the name and base URL, and fs.stats for more detailed information like: Stats { dev: 2114, ino: 48064969, ...

Non-functioning function within object

this is a unique object var Manager = (function () { var self = this; self.fetch = function (request, response) { response.send({ message: 'Data fetched successfully' }); } return self; })() module.ex ...

Trigger a JavaScript function after Angular has completed its process

Once all data binding is completed and there are no more tasks for the Angular javascript to perform, I need to execute a function that toggles the display of certain divs. Attempted Solutions I want to avoid using timeouts: The timing of Angular's ...

Set the android camera resolution to a lower setting automatically when a user attempts to upload a file from their browser

In my current application, I have implemented a feature that allows users to upload files. When the user clicks on the input field, they are presented with options to either select a video from their gallery or open the camera to record a new video and u ...

The autoIncrement feature is causing a syntax error at or near "SERIAL"

Encountering a build error : Unable to start server due to the following SequelizeDatabaseError: syntax error at or near "SERIAL" This issue arises only when using the autoIncrement=true parameter for the primary key. 'use strict'; export ...

Difficulty with rendering speed when reusing a directive in AngularJS

Here is a basic directive called "base": angular.module("base", []) .directive("base", function() { return { restrict: "A", scope: true, controller: function($scope) { this.setHeader = function(header) { $scope.h ...

In situations where there may be a duplicate, what alternative can I utilize in place of the id attribute?

I understand that almost any element in the DOM can have an "id" attribute, and I've used it to track each client in a table of clients. Although ids should not be repeated, my rows are assigned unique identifiers based on each person's "clientId ...

Using Angular JS to submit forms on a regular basis

My HTML form is set up within an Angular controller with inputs, action, and other elements already defined. The only issue I'm facing is that the form does not have a traditional submit button. Instead, there is a separate button on the page outside ...

Length Indeterminate - Pug, Express, and MongoDB

I keep encountering a persistent TypeError message stating that the length is undefined in the following code snippet. This issue is quite frustrating, especially since I've utilized the same code elsewhere in my project without any problems. users.j ...

When authenticated, the value of req.user is undefined

req.user is currently undefined even though the user is authenticated. It was functioning correctly earlier but now I'm unsure about what changes I made. Currently, it renders an empty object: {} routes/user router.get('/user', (req, res ...

The NestJS error code 413 indicates that the payload size is too large for

I am currently utilizing nestjs and have encountered an issue where an endpoint only accepts files via multipart. When attempting to upload files that are less than 10MB, everything works perfectly fine. However, when trying to upload files larger than 10M ...

using javascript to invoke php function

I encountered an issue when attempting to call a PHP function from JavaScript. The code I used is displayed below: <html> <head></head> <body> <script type="text/javascript" > function header() { <?php ...

Retrieve the current character using the jQuery keyup function

I am looking to retrieve the currently pressed keyup value: For example, in my code snippet alert("wj");, I want to extract the 'j' value as it represents the current value being pressed in the input field. I'm interested in retrieving the ...

The conversion function from string to integer is malfunctioning

I am currently working on a website where my client has the ability to modify their table_id. However, whenever I attempt to make these changes, the value in the database resets to 0. The table_id column is an integer type in MySQL, and I believe that&apos ...

Async/Await moves on to the next function without waiting for the previous function to finish executing

I am developing a web application that requires querying my database multiple times. Each query depends on the data retrieved from the previous one, so I need to ensure each call completes before moving on to the next. I have attempted using async/await fo ...

Is the accuracy of the alsoResize functionality in Jquery UI Resizable questionable?

After removing the 'alsoResize' option, I found that the behavior remains unchanged. Upon resizing the main element, I noticed that the black border of the bottom element, 'marquee,' often shifts out of alignment with the dashed white ...

"Interactive Connect 4 Game in Javascript - Drop the disk into the bottom row of the chosen

Check out this awesome Connect4 game I found: http://codepen.io/anon/pen/lmFJf I have a specific goal in mind for the game. When I click on an empty space in any column, I want it to automatically drop into the lowest available spot in that column, follow ...

Is it possible to execute custom Javascript code when navigating forwards or backwards on a webpage?

My main goal is to recreate the back button functionality using AJAX without needing to add #uglyhashes to every URL, as many solutions currently do. (Just to clarify, I am completely okay with a solution that doesn't support Internet Explorer at all ...

Changing the URL locale using Next.js router.push is unsuccessful

I am attempting to switch the locale by connecting the onClick event to two separate <div> elements: import { useRouter } from 'next/router' // other codes const router = useRouter() const changeLocale = (locale) => { router.push({ ...