Integrate SVG directly into the three.js module to eliminate the need for an additional HTTP request

Currently, I am developing a small website that features a simple 3D animation. The model is extruded from an SVG file loaded using SVGLoader. My goal is to enhance the loading speed by including the SVG as text in my threejs code, eliminating the need for a separate http request and allowing for instant execution.

What would be the best approach to achieve this? Would converting it to an STL file make the process easier?

Essentially, all I want to do is eliminate the need for a separate http request and integrate the model directly into the code.

Here is the code snippet documenting my current approach with the loader: https://github.com/riccardolardi/studioriccardolardi/blob/master/src/components/BG.svelte#L45

Thank you!

Answer №1

Utilizing the .parse() method:

body {
  overflow: hidden;
  margin: 0;
}
<script type="module">
import * as THREE from "https://threejs.org/build/three.module.js";
import {OrbitControls} from "https://threejs.org/examples/jsm/controls/OrbitControls.js";
import { SVGLoader } from 'https://threejs.org/examples/jsm/loaders/SVGLoader.js';

let scene = new THREE.Scene();
let camera = new THREE.PerspectiveCamera(60, innerWidth / innerHeight, 1, 10000);
camera.position.set(0, 10, 10);
let renderer = new THREE.WebGLRenderer();
renderer.setSize(innerWidth, innerHeight);
document.body.appendChild(renderer.domElement);

let controls = new OrbitControls(camera, renderer.domElement);
scene.add(new THREE.GridHelper());

let svg = `<svg height="250" width="500">
  <polygon points="220,10 300,210 170,250 123,234" style="fill:lime;stroke:purple;stroke-width:1" />
</svg>`;

let dirLight = new THREE.DirectionalLight(0xffffff, 1);
dirLight.position.setScalar(10);
scene.add(dirLight);
scene.add(new THREE.AmbientLight(0xffffff, 0.5));

let svgLoader = new SVGLoader();
let data = svgLoader.parse(svg);
data.paths.forEach(dp => {
  let shapes = dp.toShapes(true);
  shapes.forEach(sh => {
    let g = new THREE.ExtrudeBufferGeometry(sh, {bevelEnabled: false, depth: 2});
    g.center();
    let m = new THREE.MeshLambertMaterial({color: 0xFACE8D});
    let o = new THREE.Mesh(g, m);
    o.scale.setScalar(0.05);
    console.log(o);
    scene.add(o);
  });
  
});

renderer.setAnimationLoop(()=>{
  renderer.render(scene, camera);
});
</script>

Answer №2

By passing the SVG content as a string directly to SVGLoader.parse(), I was able to convert the SVG into shape definitions. It's worth noting that the parse method varies for each Loader in Three.js and isn't widely documented. Special thanks to Mugen87 from discourse.threejs.org for pointing this out to me.

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 2 is throwing an error: Unhandled Promise rejection because it cannot find a provider for AuthService. This error is occurring

My application utilizes an AuthService and an AuthGuard to manage user authentication and route guarding. The AuthService is used in both the AuthGuard and a LoginComponent, while the AuthGuard guards routes using CanActivate. However, upon running the app ...

(basic) Issue with Jquery ajax request not receiving data

The alert box is not displaying anything and is not returning any data from the specified URL, even though it should show the Google page! Any suggestions? I am using the POST method because I need to send querystring data as well. $.ajax({ ...

How can you personalize a website script by deactivating it using uBlock Origin and then reintegrating it as a userscript?

Can you imagine if it were possible to address a problematic portion of a script on a website by preventing the original script from loading, copying the source code, editing it, and then re-injecting it as a userscript with Tampermonkey? I attempted this ...

Ionic app encounters issue fetching local JSON data

I have been working on my Ionic application and I encountered an issue when trying to load local JSON data into it. I set up a http.get in my javascript to retrieve the data, but for some reason it's not showing up in the application. It seems like th ...

Styling a rectangle in p5.js: Tips and tricks

In my p5.js code, I created a rectangle using rect(): rect(10, 10, 10, 10); Now, I want to add some style to it with a box-shadow effect: box-shadow: 20px 20px 50px #00d2c6, -30px -30px 60px #00ffff; However, when I tried to apply the style using the doc ...

Issue with AJAX request on Internet Explorer versions 8 and 9

This script is functioning properly in Internet Explorer 10 and above, as well as Chrome and other browsers. However, it encounters issues specifically with IE8 and IE9. <table id="table" border="1"> <tbody style="display: table-row-group"&g ...

Locate all inputs containing a special attribute name, wherein a portion of the name corresponds to a JavaScript variable

$("td[id^='td' + myvar + '_']") Can someone help me with a solution to substitute the static value of 0 in this code snippet with the dynamic variable myvar? Thanks! ...

Encountering a CORS policy issue while attempting to retrieve data from an API

I have been attempting to retrieve data from the DHL API, however, I keep encountering issues due to CORS policy blocking the request. Even though I have configured the CORS policy on my backend server, the error persists. What could be the issue? Here ...

To convert an image file into a string, use JSON.stringify before including it in an AJAX request

Is it possible to send image files contained within JSON objects in an array via an AJAX call using JSON.stringify? When attempting to send the data through an AJAX call, and utilizing JSON.stringify with an array containing JSON objects that have image f ...

When using JQuery, data may not be displayed in another function even when using the same command

Hello, I'm new here and encountering a strange problem with two functions in my script. Let me show you the first function: $(document).on("click", "#result2 p", function(){ var inv_id = $(this).text(); $.get("autocomplete_inv.php", ...

Implementing Routes in Express Using Typescript Classes

Seeking assistance in converting a Node.js project that utilizes Express.js. The objective is to achieve something similar to the setup in the App.ts file. In pure Javascript, the solution remains unchanged, except that instead of a class, it involves a mo ...

Sending a variety of data inputs to an API using ajax

I am a beginner in coding and facing some challenges in troubleshooting an issue. My goal is to allow my API to accept multiple data inputs provided by the user through textarea. However, I have encountered a problem where everything works fine when only ...

Top Method for Initiating AJAX Request on WebForms Page

Looking for the best way to execute an AJAX call in a WebForms application? While ASP.NET AJAX components are an option, some may find them a bit heavy compared to the cleaner approach in MVC. Page Methods can be used, but they require static methods ...

Trouble deploying Firebase Cloud Functions

I am attempting to implement the following two functions: exports.increaseWaitinglistCounters = functions.database .ref('waitinglists/$iid/$uid') .onCreate(async () => { await admin .database() .ref(`waitinglistCounters/$ii ...

Creating dynamic templates and embellishments in VUE

My VUE components, including Field and Form, are able to dynamically render a form based on the provided data. <template> <form @submit="$emit('submit', $event)" > <template v-for="(item, index) in form.elemen ...

Utilize a randomized dynamic base URL without a set pattern to display a variety of pages

I am intrigued by the idea of creating a dynamic route that can respond to user-generated requests with specific files, similar to how Github handles URLs such as www.github.com/username or www.github.com/project. These URLs do not follow a set pattern, ma ...

What steps should I take to complete the Counting Cards challenge on freecodecamp using my own code?

Here is the issue at hand: https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-javascript/counting-cards I'm facing a problem while attempting to achieve 0 Hold in the return by using the Cards Sequence 7, 8, 9. I am aw ...

A concise way to write an else if statement in Javascript and jQuery

Is there a way to make this code more concise? It works perfectly fine, but it's too lengthy. Basically, the code involves two dropdown lists where the user selects options, and based on their selection, values appear in two textboxes. The catch is th ...

Is it possible to resolve the error message "Uncaught TypeError: Cannot read property 'node' of undefined" when utilizing d3-tip with npm?

After installing d3": "^3.5.17" and "d3-tip": "^0.7.1" via npm (d3-tip documentation), the following code was added to my index.js file: var d3 = require('d3'); var d3tip = require('d3-tip')(d3); console.log('d3 version', d3. ...

Ensuring contact form accuracy using jQuery and PHP

Can't seem to figure out why I am always getting false from the PHP file even though my contact form validation with jQuery and PHP is working fine. Let me explain with my code: Here is the HTML: <form method='post'> <label& ...