Is there a way to view 2D flat items in 3D using either babylonjs or threejs?

I am currently utilizing fabricJS and have created a variety of random drawings (such as circles, squares, and polygon shapes) on a canvas shaped like a rectangle object (Base).

My goal is to display all these drawings engraved on the main rectangle object in 3D.

Are there any libraries available that can help achieve this? I searched online and came across three.js and Babylon.js, but none of them have examples similar to what I need. I am unsure if it is even possible to accomplish this using these libraries.

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

Now, my objective is to convert these drawings into a 3D preview using a JavaScript library in the browser.

https://i.sstatic.net/N0WQL.gif

I would appreciate any guidance on how to proceed with this task.

Answer №1

Personally, I would recommend using Three.JS over BabylonJs as it is easier to handle and has a smaller size.

If you're interested, here is an example code snippet that might be helpful for achieving what you are looking for:

To transfer an SVG from FabricJS to ThreeJS, you simply need to extract the SVG and then place it in ThreeJS.

// --- Initializing the threejs scene
// ----------------------

const scene = new THREE.Scene();

const ratio = window.innerWidth / window.innerHeight;
const renderer = new THREE.WebGLRenderer({ antialias: true });

renderer.setSize(window.innerWidth, window.innerHeight);

const camera = new THREE.PerspectiveCamera(100, ratio, 0.01, 1000);
camera.position.z = 300;

document.querySelector("body").appendChild(renderer.domElement);

// Resizing and updating the camera
window.addEventListener('resize', function(e) {
  camera.aspect = window.innerWidth / window.innerHeight;
  camera.updateProjectionMatrix();

  renderer.setSize(window.innerWidth, window.innerHeight);
});

// Adding axes helper
const axesHelper = new THREE.AxesHelper(500);
scene.add(axesHelper);



// --- Main part, loading and parsing SVG
// ---------------------------------

const svgMarkup = document.querySelector('svg').outerHTML;

// Note: SVG Loader is not included in the main three.js bundle so needs to be loaded separately
// Refer to this link for more info on how to include it - https://threejs.org/docs/#examples/en/loaders/SVGLoader
const loader = new THREE.SVGLoader();
const svgData = loader.parse(svgMarkup);

// Group used for all SVG paths
const svgGroup = new THREE.Group();
// Inverting Y axis for imported SVGs
svgGroup.scale.y *= -1;

const material = new THREE.MeshNormalMaterial();

// Loop through parsed paths
svgData.paths.forEach((path, i) => {
  const shapes = path.toShapes(true);

  // Each path consists of multiple shapes
  shapes.forEach((shape, j) => {
    // Extrude each shape
    const geometry = new THREE.ExtrudeGeometry(shape, {
      depth: 20,
      bevelEnabled: false
    });

    // Creating a mesh and adding it to the group
    const mesh = new THREE.Mesh(geometry, material);

    svgGroup.add(mesh);
  });
});

// Centering elements within the group
svgGroup.children.forEach(item => {
  item.position.x -= size.x / 2;
  item.position.y -= size.y / 2;
});

// Adding the SVG group to the scene
scene.add(svgGroup);



// --- Animation loop
// ------------------

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

  // Rotating the group 
  svgGroup.rotation.y += 0.005;
  
  requestAnimationFrame(animate);
}

animate();
svg {
  display: none;
}

canvas {
  display: block;
}

a {
  font-family: Helvetica, Arial, sans-serif;
  font-size: 15px;
  padding: 10px 16px;
  display: block;
  position: fixed;
  bottom: 0;
  right: 0;
  color: #ddd;
  transition: all 0.25s;
}

a:hover {
  color: #3498db;  
}
<script src="https://unpkg.com/three@0.131.3/build/three.js"></script>
<script src="https://unpkg.com/three@0.131.3/examples/js/loaders/SVGLoader.js"></script>

<svg width="202px" height="202px" viewBox="0 0 202 202" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
      <path fill="none" d="M201,1 L201,201 L1,201 L1,1 L201,1 Z M53.27053,71 L37.6666667,71 L37.6666667,134.333333 L53.27053,134.333333 L53.27053,86.6038647 C59.2367133,86.879227 66.1207733,91.1014493 66.1207733,99.9130433 L66.1207733,134.333333 L80.4396133,134.333333 L80.4396133,99.9130433 C80.4396133,91.1014493 87.32367,86.879227 93.2898567,86.6038647 L93.2898567,134.333333 L110.63768,134.333333 L110.63768,86.6038647 C116.603863,86.879227 123.487923,91.1014493 123.487923,99.9130433 L123.487923,134.333333 L137.806763,134.333333 L137.806763,99.9130433 C137.806763,91.1014493 144.69082,86.879227 150.657003,86.6038647 L150.657003,134.333333 L166.26087,134.333333 L166.26087,71 L150.657003,71 C142.120773,71 133.859903,75.589372 130.647343, 80.178744 C127.434783,75.589372 119.173913,71 110.63768,71 L93.2898567,71 C84.7536233,71 76.4927533,75.589372 73.2801933,80.178744 C70.0676333,75.589372 61.8067633,71 53.27053,71 Z" stroke="#979797"></path></svg>

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

How can I customize the visibility toggles for the password input field in Angular Material?

Currently immersed in the Angular 15 migration process... Today, I encountered an issue with a password input that displays two eyes the first time something is entered in the field. The HTML code for this is as follows: <mat-form-field appearance=&qu ...

Comparative analysis within the JSON object

I have a sample JSON object with the following format: var data = [{"value":"S900_Aru","family":"S400"}, {"value":"S500_Aru","family":"S400"}, {"value":"2610_H","family":"A650"}] The first two values are related to the same f ...

The background image's fadeInOut transitions create a strange phenomenon where all the text appears in white

So, here's a strange issue I'm facing. On my website, the background image changes with a smooth fadeIn/Out transition. Video: Website in action: Here is the HTML markup: <div class="fondo" onclick="descargar(2,500);descargar(1,500);"> ...

Steps to resolve the Uncaught SyntaxError: Unexpected token o in JSON at position 1 issue

$.ajax({ url: "/url/url.ajax?length=100000&startDate=2018-07-01", method: "get", dataType: "json", success: function (jdata) { var jsonData=JSON.parse(jdata.data); ...

What are the steps to creating a screen that mimics a mirror in the physical world?

Is there a way for the user to see themselves when they open a URL? I'm not looking for a mirror effect like the one produced by jQuery reflection js. I don't want to rely on using the front camera or any other camera to achieve this. Any sugges ...

Is it possible to store Socket.IO responses in a cache for quicker retrieval?

Consider this scenario where I have a websocket implementation shown below: let itemsArray = []; function fetchData() { itemsArray = await db.query(`SELECT * FROM Items`); } function emitData() { io.sockets.in("room_foo").emit("data", JSON.stringify ...

Using jQuery ajax links may either be effective or ineffective, depending on the scenario. At times

Can someone please assist me in understanding why an ajax link may or may not work when clicked? It seems to function intermittently. window.onload = function(){ function getXmlHttp(){ ...... // simply ajax } var contentContainer = ...

Using JavaScript's regular expressions to identify a code block that commences with a specified pattern

Currently, I am working on a JavaScript script and I am in need of a Regex pattern to quickly match "JSDocs". The specific pattern that I am trying to match looks like this: # this is block1 /// text /// text /// text /// text # this is block2 /// text // ...

Use ng-class in a P tag to assess a variety of expressions

Is there a way to apply ng-class to automatically evaluate negative values within a < p > tag? <p <strong>LW$:</strong> {{d.lw_metric}} <strong>LW:</strong> {{d.lw_metric_percentage}} <strong>L4W:</strong> {{ ...

"Threlte three.js Brings a Fresh Perspective with Subtle Hue Shifts

Struggling to create a skybox similar to the one shown in this video using Threlte, but the colors keep appearing washed out. View of image in vscode: https://i.sstatic.net/N89Qi.jpg Image as a texture: imgur link +page.svelte: <script> import ...

Discovering the required rotation angle for an object to directly face another using JS HTML5 CANVAS

Hey there, I'm currently working on a game project in Javascript where I have a player and a cursor. I already know the positions of both objects, but what I need help with is determining the angle in degrees or radians that the player needs to rotate ...

Blend multiple images using Angular

Is there a way to combine multiple images in Angular? I came across some HTML5 code that seemed like it could do the trick, but unfortunately, I couldn't make it work. <canvas id="canvas"></canvas> <script type="text/javascript"> ...

I would like to inquire about the process of accessing profile information on a website through the LinkedIn API

Do you know how I can use the latest LinkedIn JavaScript API with OAuth 2.0 to retrieve my own profile details for a website? The goal is to automatically update the website using my linked profile information. I have attempted the following: api_key: ...

Ways to resolve the issue "Module Not Found Error: Cannot locate module './src/bot/index'"

Whenever I run the command node src/index.js I encounter the following error message: Error: Cannot find module './src/bot/index' Require stack: C:\Users\MIMAR\Desktop\EJS\src\index.js What could be causing this er ...

Issue with Material UI components: The Select component is collapsed and the autoWidth functionality is not

The Material UI (React) Select component is not expanding in width as expected, even with the autoWidth property. https://i.sstatic.net/h3H0V.png <FormControl margin="dense"> <InputLabel id="prefix-label">Prefi ...

The coordinates of the object's location do not align with the parameters set in the box3.set

I am currently working with a loaded object (stl file) and attempting to implement a 'snapping' effect when dragging it around. As part of my process, I am using a THREE.Box3 to perform some detection tasks. However, I have noticed that the posi ...

What benefits does JavaScript offer with the strategy of storing functions within variables?

Lately I've come across some code where functions are being stored inside variables and then called in the typical way. For example: var myFunctionName = function() { Code Here... } myFunctionName(); I'm aware that there may be numerous b ...

Deleting an element from a JavaScript array

I have a collection of javascript functions that manage intervals by setting and clearing them. The intervals are stored in an array called intervals[]. config: { settings: { timezone: 'Australia/Perth,', base_url: location.p ...

I'm having some trouble with this error while trying to install nodemon globally using npm. How can I troub

Currently, I am diving deep into node js and express. However, I have encountered persistent error messages while trying to install 'nodemon'. What type of error message am I dealing with here? How can I troubleshoot and resolve this issue? Whic ...

Are JQuery functions affected when navigating between pages in smart-tables?

Apologies if this question has been answered before or seems obvious. I couldn't find a solution after searching, and as someone new to web development, I might be going in circles here. Issue: I've integrated the smart-table extension () into ...