I am having trouble running my JavaScript code outside of JSFiddle

It's strange how my code functions perfectly in JSFiddle, but when I attempt to use it outside of JSFiddle, it fails to work. Can anyone provide a solution or insight into what might be causing this issue? Feel free to check out the JSFiddle code here: http://jsfiddle.net/56yK9/12/

If you visit the JSFiddle link, make sure to click "run" after the page has finished loading.

If you'd like to view the code from my html document, you can find it here: http://pastebin.com/D9eeVysr

Answer №1

Check out this code snippet for some help: http://jsfiddle.net/ebeit303/e5Q3N/1/

<!DOCTYPE html>
<html lang="en>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
    <script src="http://cdnjs.cloudflare.com/ajax/libs/jquery/2.0.3/jquery.min.js" ></script>
    <script src="http://cdnjs.cloudflare.com/ajax/libs/three.js/r61/three.min.js" ></script>
</head>
<body >
    <script>
        var container;
        var camera, scene, renderer;
        var group;

        container = document.createElement('div');
        document.body.appendChild(container);
        $(document).ready(function() {
            try {
                init();

            }
            catch (e) {
                container.innerHTML = e.toString();
            }
        });
        function init() {
            // Setting up renderer
            renderer = new THREE.WebGLRenderer({antialias: true});
            renderer.setClearColorHex(0xADD8E6, 1);
            renderer.setSize(window.innerWidth, window.innerHeight);
            container.appendChild(renderer.domElement);

            // Setting up camera
            camera = new THREE.PerspectiveCamera(60, window.innerWidth / window.innerHeight, 1, 2100);
            camera.position.z = 1000;

            scene = new THREE.Scene();

            group = new THREE.Object3D();
            scene.add(group);

            var tUrl = "http://www.mediafire.com/convkey/7344/ra2l3kgscpvjflafg.jpg";
            var texture = THREE.ImageUtils.loadTexture(tUrl, {}, spriteMesh);

            window.addEventListener('resize', onWindowResize, false);
            animate();
        }
        function spriteMesh(ashTexture) {
            // Creating sprites
            var ashMaterial = new THREE.SpriteMaterial({map: ashTexture});
            var Ash = new THREE.Sprite(ashMaterial);
            var imageWidth1 = ashMaterial.map.image.width;
            var imageHeight1 = ashMaterial.map.image.height;
            Ash.scale.set(3 * imageWidth1, 3 * imageHeight1, 1.0);
            Ash.position.set(2 * imageWidth1, 2 * imageHeight1, 1.0);
            group.add(Ash);
        }
        function onWindowResize() {
            camera.aspect = window.innerWidth / window.innerHeight;
            camera.updateProjectionMatrix();
            renderer.setSize(window.innerWidth, window.innerHeight);
        }

        function animate() {
            requestAnimationFrame(animate);
            update();
            render();
        }
        function update() {
            camera.lookAt(scene.position);
            camera.updateProjectionMatrix();
        }
        function render() {
            renderer.render(scene, camera);
        }

    </script>
</body>
</html>

Answer №2

The issue with your HTML document is that imageWidth and imageHeight are both equal to 0. This is because the other functions or code in your document do not wait for the image to load from the site, causing the sprite to be invisible. You may need to make some changes to your code in order to address this.

var texture = THREE.ImageUtils.loadTexture(tUrl, {}, callback);
callback = function(texture){
........insert your code here...........
}

Take a look at the code in the provided link for some insights on image and texture loading:

Answer №3

It appears that you may be missing a necessary on page load or ready handler.
Check out this example which demonstrates at least some functionality:

http://pastebin.com/HjkRgP5A

For a cleaner presentation of your jsfiddle project, you can view it here:
jsfiddle.net/12HgJ/show/

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

Is there a way to display an animation when a page loads using jQuery that only plays for index.php and not other_page.php?

How can I trigger an animation on page load, specifically for my index.php page and not all other pages on my website? Is there a jQuery function that targets only the index.php page like this: $('index.php').ready(function()); If not, what i ...

Is it advisable to incorporate vue-resource in Vuex actions?

I am currently working on a web application that retrieves airport data from the backend. To manage states and data sharing, I am utilizing Vuex. My dilemma is whether to load the airports in my Vuex actions or within a method of my Vue instance which will ...

The asynchronous functionality for reading and writing files from 'fs' is not functioning properly

I've been working on a script that reads and writes files, and so far the functions are functioning properly. However, I am facing challenges in making the read/write functions asynchronous. The main issue arises when trying to write a file and then i ...

Using JQuery to loop through elements when clicked

I've been experimenting with different methods to iterate through a series of 4 li elements, each having a class of "item_n" where n is a number from 1 to 4. I want the iteration to increase by 1 with every click. Despite my efforts, my code isn' ...

Leveraging python capabilities within html documents

English is not my first language, so please excuse any spelling errors. I am working on combining HTML and Python to develop a graphical user interface (GUI) that can communicate with a bus system (specifically KNX bus). Currently, I have a Raspberry Pi ...

Searching with jQuery UI Autocomplete

I am interested in implementing jQuery UI autocomplete to allow users to search for items on my website. I have a list of products that I want to convert into JSON data (or just include them directly in JavaScript like the jQuery UI demo does), but I&apos ...

Having difficulties retrieving JSON data

I'm encountering an issue while trying to retrieve my JSON data using an AJAX request. JSON { "Ongoing": [ {"name": "meh"}, {"name": "hem"} ], "Completed": [ {"name": "kfg"}, {"name": "dkfgd"} ] } ...

Deeply nested .map function to update state value

The current state value const [settings, setSettings] = useContext(SettingsContext) Utilizing the .map method on the settings state {settings[categoryIndex]?.config?.map((item: ConfigItem, index: number) => ...

Tips for Loading an Alternate JavaScript File When the Controller Action Result is Null

My controller action is located in *controller/books_controller.rb* def search_book @found_book = Book.find_by_token(params[:token_no]) # After the book is found, I render the search_book.js.erb file using UJS respond_to do |form ...

Upcoming verification with JSON Web Token

I am looking to incorporate JWT auth into my Next app. Currently, I have mapped out the flow as such: User enters email and password to log in Server responds with status 200 and a jwt access token in httpOnly cookies My main dilemma lies in deciding on ...

Transferring information between different parts of a system

I have created a component that includes a state called chosenGenre, along with a function that updates this state based on button clicks. My goal is to access the updated state (which is of type string) in another component. This is the initial componen ...

How can one overcome CORS policies to retrieve the title of a webpage using JavaScript?

As I work on a plugin for Obsidian that expands shortened urls like bit.ly or t.co to their full-length versions in Markdown, I encounter a problem. I need to fetch the page title in order to properly create a Markdown link [title](web link). Unfortunatel ...

Making a Request on Behalf of a Component in Vue.js Using Interceptors

Within my Vue application, I've implemented a response interceptor: axios.interceptors.response.use(function (config) { return config; }, error => { if (error.response.status !== 401) { return new Promise((resolve, ...

Input specific ng-if conditions

I'm a bit confused about the conditions for my ng-if and could use some assistance. I have a form on my page that is rendered using ng-repeat and a couple of custom filters. You can check out this plunker. The issue I'm facing is that I need to p ...

When a Javascript function marked as async is executed, it will return an object

Async function is returning [object Promise] instead of the desired real value. Interestingly, I can see the value in the console log. It seems like this behavior is expected from the function, but I'm unsure how to fix my code. This code snippet is ...

Sort data by various categories using Vue.js

I need help filtering my JSON data based on multiple categories using Vuejs, specifically with Vue 3 and collect.js. Here's the template I'm working with: <select v-model="selectedCategory" multiple> <option :value="n ...

Struggling to implement a seamless scrolling effect using CSSTransition Group

In my quest to achieve a smooth vertical scroll effect for content appearing and disappearing from the DOM, I've turned to CSSTransitionGroup (or ReactTransitionGroup). While I'm familiar with CSS animations for such effects, I need to implement ...

When implementing javascript_pack_tag in Rails, an EOFError may occur

It seems like the files in public/packs/js are having trouble loading. Here are the javascript tags being used in the view: = javascript_include_tag 'application' = javascript_pack_tag 'application' The error displayed in the browser ...

The Vue DevTools are functioning as expected, but there seems to be an issue

Encountering a peculiar issue where the value displayed in Vue DevTools is accurate, matching what is expected in my data. When I first click on the "Edit" button for an item, the correct value appears in the browser window as intended. However, upon clic ...

The Handlebars template remains blank, failing to show any data or error messages

//////////////////////////////////// // Function to append items // ////////////////////////////////// function addItems(data) { var template = document.getElementById('items').innerHTML; var handlebarsTemplate = Handlebars.compile(tem ...