Tips for creating an SVG element on a plane using THREE.js

I am attempting to duplicate an existing svg element within a THREE.js environment. Following this example, I convert the svg to an image, create a plane with a texture based on the image, and then add it to the scene. However, I am encountering an issue where the plane appears black. When I replace the texture with a solid color, it renders correctly, indicating there might be an issue with the texture itself.

        var legend = document.querySelector("svg.ViewLegend");
        var svgData = new XMLSerializer().serializeToString(legend);

        var canvas = document.createElement("canvas");
        canvas.width = 512;
        canvas.height = 64;
        var ctx = canvas.getContext("2d");

        var img = document.createElement("img");
        img.setAttribute("src", "data:image/svg+xml;base64," + btoa(svgData));

        img.onload = function () {
            ctx.drawImage(img, 0, 0);

            var texture = new THREE.Texture(canvas);
            texture.needsUpdate = true;

            var material = new THREE.MeshBasicMaterial({
                map: texture,
            });
            material.map.minFilter = THREE.LinearFilter;
            //If I use the material below, it works correctly
            //var material = new THREE.MeshPhongMaterial({color: 0xCC0000});
            var geometry = new THREE.PlaneBufferGeometry(512, 64, 1, 1);
            var mesh = new THREE.Mesh(geometry, material);

            scene.add(mesh);
        };

Answer №1

It is my understanding that you must execute the following steps:

var canvas = document.createElement("canvas");
var svgSize = svg.getBoundingClientRect();
canvas.width = svgSize.width;
canvas.height = svgSize.height;
var ctx = canvas.getContext("2d");

var img = document.createElement("img");
img.setAttribute("src", "data:image/svg+xml;base64," + window.btoa(unescape(encodeURIComponent(svgData))) );

img.onload = function() {
  ctx.drawImage(img, 0, 0);

  var texture = new THREE.Texture(canvas);
  texture.needsUpdate = true;

  var geometry = new THREE.SphereGeometry(3, 50, 50, 0, Math.PI * 2, 0, Math.PI * 2);
  var material = new THREE.MeshBasicMaterial({ map: texture });
  material.map.minFilter = THREE.LinearFilter;
  mesh = new THREE.Mesh(geometry, material);
  scene.add(mesh);
};

View the working example at: http://jsfiddle.net/3Lg911vs/4/

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

Discover the best way to transfer hook values to CreateContext in React

In my project, I've implemented a component called SideBarBlurChange. Within this component, there is a requirement to pass a value named values inside the BlurChangeValue array, which is nested within the CreateContext. I have searched online for ex ...

Creating a universal header for all webpages in Angular JS by dynamically adding elements using JavaScript DOM manipulation techniques

I have successfully created a json File containing an array of "learnobjects", each including an id, name, and link. Check out my plnkr example var myMessage = { "learnobjects": [{ "id": "1", "name": "Animation-Basics", "link": "animation_bas ...

JavaScript: Repeated Depth First Exploration for hierarchical rearrangement implemented with d3's recursion()

I'm attempting to perform a depth-first search on a complex JSON object, such as the one available through this link. My goal is to generate a modified object structure that looks like this: [ { name: "Original Object", children : [ ...

React is producing a collection of <td>'s

My React code is very straightforward and it runs smoothly: function Columns(){ return ( <React.Fragment> <li>Hello</li> <li>World</li> </React.Fragment> ); } function Example(){ ...

Issues with sending FormData through Ajax POST requests over a secure HTTPS connection

We are currently experiencing issues with uploading pictures to our server. The process works smoothly on http sites, but encounters errors on https sites. An error message is displayed:https://i.sstatic.net/hPMZv.png Failed to load resource: the server r ...

Leveraging external data for testing in Protractor script

I am encountering an issue while attempting to access test data using JSON, as it keeps showing up as undefined. I am implementing a Page Object Model and trying to reference external test data. However, when passing the values from my test data into a fun ...

Utilize flexbox to create a list that is displayed in a column-reverse layout

I am facing a challenge in displaying the latest chat person in the 1st position (active) using Firebase. Unfortunately, Firebase does not have a date field which makes it difficult to achieve this. I have attempted converting the date into milliseconds an ...

Dynamic sidebar that adheres to the content and is placed alongside it using JavaScript

I am in need of creating a sticky sidebar that will float beside my content column. The purpose of this sidebar is to contain jump links on the page, similar to what can be seen on this page, but with the navigation buttons positioned directly next to the ...

Experience seamless slide transitions with the react-slick carousel using scroll events in React JS and JavaScript

Currently utilizing the carousel library found at: react-slick I am interested in enabling mouse scroll functionality to navigate through each slide. The idea is to scroll up to progress forward and scroll down to go backward. Came across a relevant exa ...

IE8 is encountering a null JSON response from the HTTP handler, unlike IE10 and Chrome which are not experiencing this

Here is my JavaScript code snippet: patients.prototype.GetPatient = function(patient_id,callback) { var xmlhttp; var fullpath; try { if (window.XMLHttpRequest) { xmlhttp = new XMLHttpRequest(); } else { ...

various stunning galleries accessible from a single page of thumbnail images

I'm trying to create a unique gallery experience on my website. I have a set of 6 images, each featuring a different house. What I want is for each image, when clicked, to open up a fancybox gallery showcasing 4 more detailed photos of the same house. ...

How can I choose the div that is in the same container class div as this using Jquery?

As I cycle through data within a foreach loop, each iteration populates a container class as shown below: foreach($resultarray AS $value){ $filename = substr($value['img_file_name'],9); $cat_id = $value['cat_id']; ...

Guide to showcasing a component in reactjs based on a conditional statement?

Here is an example of code snippet. import React, { Component } from "react"; import Navpills from "./Navpills"; import Home from "./pages/Home"; import About from "./pages/About"; import Blog from "./pages/Blog"; import Contact from ". /pages/Contact"; ...

Setting a condition for a function call when a checkbox is clicked

My table has columns labeled NoBill and Bill, with checkboxes as the values. Here is the default view of the table: https://i.stack.imgur.com/ZUvb2.png When the checkbox in the NoBill column is clicked, the total value (this.total) is calculated. The t ...

Exploring the process of sending JSON responses through Express

I recently started working with node/express. My express app has a single post route ('/'), which is designed to retrieve information about GitHub users based on their usernames. For instance, when I make a post request like this { "develop ...

Exploring Next.js' dynamic routes with an alternative URL approach

Currently in the process of transitioning a React project to Next.js, I've encountered a minor issue with Dynamic Routing that doesn't seem to have any readily available solutions online. I have multiple information pages that utilize the same c ...

React: Assigning a unique className to an element in a list

In the code snippet below, I am attempting to add a className based on the state of the checkbox. While the className is being added correctly, the issue arises when it gets applied to all elements in the list upon checking/unchecking any checkbox. I aim ...

Intersection Observer API is not compatible with the functionality of the navigation bar

Having trouble with the Intersection Observer API. Attempting to use it to show a nav-bar with a white background fixed to the viewport once it scrolls out of view. Initially tested using console.log('visible') successfully to determine visibili ...

Switching between API requests through a live feed

Hey there: import Rx from 'rxjs'; function mockApi(endpoint, time, response) { return new Rx.Observable(observer => { console.log(`${endpoint}: Request initiated.`) let active = true; const id = setTimeout(() => { cons ...

Ways to calculate the total number of keys within a JSON object at a certain level

I need to process a JSON file by extracting values from keys located at a specific depth. The initial value I want to access is situated here: json.children[0].children[0].children[0] Is there a method to navigate through the JSON object at a particular ...