Issue with Three.js not displaying graphics on current canvas

I have set up a canvas with the ID of 'canvas' and passed it as an argument to the WebGLRenderer in Three.js. However, I am not seeing anything displayed on that canvas. When I append the domElement to the document, the canvas appears at the bottom, but I want to draw on my existing canvas instead. Do I need to adjust any additional settings?

Here is the code snippet I am starting with:

ctx = $('canvas').getContext('2d');
var canvasElm = $('canvas');
canvasWidth = parseInt(canvasElm.width);
canvasHeight = parseInt(canvasElm.height);
canvasTop = parseInt(canvasElm.style.top);
canvasLeft = parseInt(canvasElm.style.left);

var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera(75, canvasWidth / canvasHeight, 0.1, 1000);

var renderer = window.WebGLRenderingContext ? new THREE.WebGLRenderer(canvasElm) : new THREE.CanvasRenderer();
renderer.setSize(canvasWidth, canvasHeight);

var geometry = new THREE.CubeGeometry(20, 20, 20);
var material = new THREE.MeshBasicMaterial({ color: 0x0000FF });
var cube = new THREE.Mesh(geometry, material);
scene.add(cube);

camera.position.z = 50;

var render = function () {
cube.rotation.x += 0.01;
cube.rotation.y += 0.01;

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

render();

I am using Chrome version 56.0.2924.87 (64-bit) for reference.

Answer №1

It seems like your jquery selector is incorrect (assuming it's jquery).
var canvasElm = $('canvas'); actually creates a new canvas element.
If you intend to select a canvas with the id of 'canvas', you should use..
var canvasElm = $('#canvas');
However, this returns a jquery object / list, so to access the actual canvas (the first item in the list), you could do..
var canvasElm = $('#canvas')[0];

For example:

var canvasElm = $('#canvas')[0];
renderer = new THREE.WebGLRenderer( { canvas: canvasElm } );

In this case, it might be more efficient to simply use plain JavaScript without jquery.
For instance:

canvasElm = document.getElementById('canvas');
renderer = new THREE.WebGLRenderer( { canvas: canvasElm } );

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

Angular's $http.get method allows you to make HTTP

My goal is to display all lists and the tasks associated with each list. In my controller, I have the following code: $http.get('api/list/').success(function (data) { $scope.lists = data; $scope.tasks = data[0].Task; ...

Switch to a different form when clicked using JavaScript

Can you assist me with my code issue? The scenario is as follows: I have two forms - one for registration and one for login. I want to dynamically replace the login form with the register form when the user clicks on the "Sign up" link. Similarly, if the ...

Using AngularJS $http to retrieve data from an ExpressJS endpoint: A comprehensive guide

Here is an example of an ExpressJS route: var exec = require('child_process').exec; app.get('/someURL', function (req, res) { exec('cp file1 file2', (err, stdout, stderr) => { if (err) { // node co ...

What steps can be taken to ensure that the JavaScript fetch() function is consistently accessing and updating the new data that is being added to the

I'm facing an issue with my JSON data file that I want to display on the screen. I have a function with a fetch() request that executes every time I click a button. Initially, it works perfectly by fetching the data and displaying it correctly. Howeve ...

Tips for implementing a minimum character length feature in React Material-UI's Autocomplete feature

I am looking to add a 'minimum character length' feature to the autocomplete component in react material-ui. The code snippet below demonstrates what I have so far. constructor(props) { super(props); this.state = { // toggle for ma ...

What is preventing the items inside the <ul> element from displaying?

Struggling to grasp pagination, I can't figure out why the contents of "li" under the "ul" disappear while the "ul" container continues to display despite specifying in the JavaScript that only 6 should be visible on the page. The "ul" and "li" elemen ...

Create a dynamic animation using three.js

I am currently developing an application that optimizes pack placement in a truck using three.js for displaying 3D results. Below is the code snippet I'm working with: My goal is to create a moving scene where boxes are displayed one by one and move ...

When a specific option is selected in a `select` element with the `multiple` attribute, activate the change event

Is it possible to trigger a change event on individual options within a standard select element using jQuery or another method? I want the change event to be triggered on the option elements themselves rather than on the select element, as multiple options ...

Enhancing user experience with a jQuery autocomplete feature for dual language support

There are two input fields, one for English and the other for Spanish. {!! Form::text('titulo_en', null, array('placeholder' => 'Title','class' => 'form-control buscador')) !!} {!! Form::text('t ...

react.js function that returns 'undefined'

Having trouble with my class function that returns undefined when I try to use the return value. Main.js: let db = new Database() let username = db.get() return( //returns undefined <p>{username}</p> ) database.js: class Database { [... ...

What is the proper way to update a dropdown value in a React JS component?

Can you please guide me on how to assign a value in a dropdown in react js? I am retrieving the dropdown data after a delay of 3000 milliseconds and then I need to set a value in the dropdown. const App = ({ children }) => { const val = "ax"; const ...

How can I style the inner div by adding a class to the first div?

In my project, I have a list of elements that are generated dynamically, all styled the same way but with different content. The first element has a specific styling, and if it doesn't render, I want the second element to inherit that styling. < ...

Transform the API response into a map in Angular version 16

When I receive a JSON response from a Java server, the structure looks like this: { "summary": { }, "runs": { "key_1": { "object_1": { }, "object_2": { ...

Reverse lookup and deletion using Mongoose

Currently, I am attempting to perform a health check on the references within one of my collections. The goal is to verify if objects being referenced still exist, and if not, remove that particular _id from the array. Despite my efforts, I have not come ...

Identify unique MongoDb instances within an array of data

My list contains various unique items - search = alluk.distinct('Object of search') I am interested in counting each item individually. Presently, I am counting them manually in the following way - alluk.find({'Object of search':&ap ...

What is the best way to implement a timer or interval system in React and Next.js that continues running even when the tab is not in focus or the browser is in

I am attempting to create a stopwatch feature using next js. However, I have encountered an unusual issue where the stopwatch does not function correctly when the tab is not focused or when the system goes to sleep or becomes inactive. It appears that the ...

In Javascript, an error occurs when something is undefined

I've been grappling with a Javascript issue and seem to have hit a roadblock. In Firefox's console, I keep encountering an error message that says "info[last] is undefined," and it's leaving me puzzled. The problematic line appears to be nu ...

Can I incorporate the name of my web application into the URL using Node.js?

Is it possible to include my web app name in the URL using Node.js? Currently, my web app runs on I am looking to have the pathname /myapp added like so: ...

Sending input data without a form

Currently, I am in the process of developing a website game and facing a challenge with implementing a feature I refer to as "dialogue". Initially, I attempted to address this issue by using a form element, but encountered a problem where pressing enter o ...

What is the most effective method for assessing a service using angular?

As a beginner in angular testing, I am eager to start creating tests for my service. However, I have encountered an issue where my service (foo) injects another service (bar) in its constructor. Should I create a mock for bar? Do I need to mock every func ...