Using JSON data to render images onto a canvas

I am encountering an issue with a JSON array that I'm receiving from PHP. The array is indexed and has the following format (larger in real scenario)

 [
        [
            [17, 28, 1, "z"],
            [28, 31, 6, "b"],
            [8, 29, 6, "b"]
        ],
        [
            [19, 28, 1, "z"],
            [17, 25, 6, "b"],
            [19, 25, 6, "b"],
            [27, 32, 6, "b"],
            [9, 28, 6, "b"]
        ]
    ]  

When trying to process this json array, I encounter an error when passing values into the drawImage parameters. The console shows the following message:

TypeError: Value could not be converted to any of: HTMLImageElement, HTMLCanvasElement, HTMLVideoElement.

alert(typeof data); //object

$(document).ready(function() {
        canvas = document.getElementById("myCanvas");
        ctx = canvas.getContext("2d");

            r = new Image()
            r.src = 'graphics/redsprites.png';
            image2 = new Image()
            image2.src = 'graphics/pitch.png';
            b = new Image()
            b.src = 'graphics/bluesprites.png';
            z = new Image()
            z.src = 'graphics/zoxball.png';
            var nextFrame =0;
            var m;

    foo(function(data) {
            alert(typeof data);
            var draw = function(){
            ctx.clearRect(0, 0, 1080, 1680);
            ctx.drawImage(image2, 0, 0, 622, 924, 0, 0, 1080, 1680);
            if (nextFrame<=10){
                for(m = 0; m <=22; m++)//23 is 22 players plus ball
                {
                alert(m);
                alert(nextFrame);
                alert(data[nextFrame][m][0]);
                alert(data[nextFrame][m][1]);
                alert(data[nextFrame][m][3]);
                ctx.drawImage(data[nextFrame][m][3], 0, 0, 100, 100, data[nextFrame][m][0], data[nextFrame][m][1], 25, 25);
                }
            }else{
                clearTimeout(draw);
            }
            nextFrame++;        
            }
            setInterval(draw,1000); 

        }); 


    function foo(callback) {
        $.ajax({
                type: "POST",
                url: "matchEngine.php",
                success:function(data) {

                    for (var i = 0, len= data.length;i <len; i++) {
                    for ( h = 0, len2= data[i].length;h <len2; h++) {
                    //alert("am here!!");
                    data[i][h][0]=(data[i][h][0])*30;
                    data[i][h][1]=(data[i][h][1])*30;
                    data[i][h][3]=data[i][h][3].replace(/\"/,"");
                    }
                    }
                    callback(data);
            }
        });
    }

});     

Why are the parameters for the drawImage not working??

Answer №1

Do you need to access this information:

data[nextFrame][m][3]

What you actually receive is the character “r” itself, not the visual content stored in the variable “r”.

There are various methods to store/retrieve the image represented by the index-letter “r”.

One approach involves creating an object (named images) and including a component named "r" that contains the desired image.

// initiate a new object where all images will be kept

    var images=new Object();

// insert a new image labeled as “r” into the images object

    images.r=document.createElement("img");
    images.r.src=”graphics/redsprites.png”;

FYI, there is a Chrome bug that necessitates using createElement instead of new Image(). Hence why createElement is used here.

Then to retrieve the “r” image for your drawImage function with the key "letter-r" like so:

ctx.drawImage( images["r"], 0,0);

By integrating your JSON data, this function operates smoothly:

ctx.drawImage(images[  data[nextFrame][m][3]]  ], 0, 0);

Below is the code snippet and a Fiddle link: http://jsfiddle.net/m1erickson/mE9VC/

<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" media="all" href="css/reset.css" /> <!-- reset css -->
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>

<style>
    body{ background-color: ivory; }
    canvas{border:1px solid red;}
</style>

<script>
$(function(){

    var canvas=document.getElementById("canvas");
    var ctx=canvas.getContext("2d");

    var images=new Object();
    images.r=document.createElement("img");
    images.r.onload=function(){

        ctx.drawImage(images['r'],0,0);

    }
    images.r.src="https://dl.dropboxusercontent.com/u/139992952/stackoverflow/house-icon.png";


}); // end $(function(){});
</script>

</head>

<body>
    <canvas id="canvas" width=300 height=300></canvas>
</body>
</html>

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

The jquery autocomplete feature is failing to display search results

I have a text input with autocomplete functionality using JavaScript: JavaScript code: $("#descSearchBox").keyup(function(e) { $(".ui-autocomplete").removeClass("ui-autocomplete ui-front ui-menu ui-widget ui-widget-content ui-corner-all") .ad ...

AngularJS blank drop-down selection

I am currently working on an AngularJS select element with ng-options using the code below: <select ng-model="vm.selectedship" ng-change="vm.updateShip()" data-ng-options="ship as ('ship' + ' is ready (' + ship.currentlocation + & ...

Retrieve the present value from a Selectpicker using jQuery within the Codeigniter Framework

I attempted to use DOM manipulation to retrieve the value of the currently selected option from the selectpicker. My goal was to have the value of the selectpicker id="service_provider_select" printed first. However, whenever I changed the option using the ...

Tips for displaying JSON data in HTML without the use of placeholder DIV elements

Customer Scenario: A user wants to search through Wikipedia. The search results should be limited to 5 articles, and the user should be able to view the title and introduction of each article. Developer Scenario: User input is provided via an HTML input f ...

Determining the quantity of items within a div using jQuery

Similar Question: Retrieve the count of elements inside parent div using jQuery Can you determine the total number of elements within a specific div? <div id=count"> <span></span> <span></span> <span></ ...

Unable to access image from JSON within Mobile Angular Ui utilizing Angular Js

Currently, I am able to retrieve various data from JSON such as Price and Display Order, but I am facing difficulty in fetching the image. HTML: <div ng-controller="chooseProductDescription"> <div ng-repeat="cat in productDescrip ...

Operating PHP program from html on Beaglebone Black Rev C Debian

I've created a JavaScript program that utilizes node.js to manage GPIO from an IO.html page to the beaglebone. I simply initiate the JavaScript with "node myscript.js". Now, I'm looking to incorporate a PHP file that will store data from the IO. ...

What is causing elements like divs, paragraphs, or text not to display within an ion-item after an ion-input is added?

I am currently working on validating a simple form and everything seems to be functioning properly. However, I have encountered an issue with displaying text messages within an ionic 3 list item. The ion-item consists of an ion-input element. When I place ...

Ways to transform the DropBox chooser button into an image

I'm looking to incorporate an image in place of Dropbox's default chooser button. Despite reviewing their API documentation, I haven't come across any methods to use alternative elements for the Dropbox chooser. Does anyone have a solution f ...

Experience the power of ReactJS as you utilize the componentDidMount lifecycle method to fetch data

Currently, I am in the process of learning how to utilize ReactJS, Spotify API, and Promises. My goal is to retrieve top albums from musicians on Spotify and play a 30-second snippet of their tracks. I have decided to work with a Spotify package known as ...

Recoil: Executing a function when an atom is modified

My goal is to store a user object in an atom and cache it in localStorage every time it changes to avoid having the user sign in repeatedly if the app crashes: localStorage.setItem('user', JSON.stringify(user)) Previously, with useContext, I ach ...

I often find myself pondering the significance of objects such as [, thisArg]

At times, I delve into JavaScript code on MDN and come across some confusing syntax like [, thisArg]... for instance, arr.map(callback(currentValue[, index[, array]])[, thisArg]) In this scenario, I am aware that a callback function is required. But what ...

React 18 doesn't trigger component re-rendering with redux

In my code, I have implemented a custom hook to handle global data fetching based on user authentication. Here is an example of the hook: const userState = useSelector(state => state.user.state) useEffect(() => { if(userState === "authentic ...

Could anyone clarify the concept of how a function is able to be equivalent to zero?

function checkForSpecialCharacters(text) { var specialChars = [";", "!", ".", "?", ",", "-"]; for(var i = 0; i < specialChars.length; i++) { if(text.indexOf(specialChars[i]) !== -1) { return true; } } ...

Tips for showcasing MySQL JSON data

There is a table in my database called purchase, where I insert data in JSON format. The JSON format contains multiple sets of data, for example, "products" has 2 items. https://i.stack.imgur.com/NJ5qz.png [{"products":["Asulak Silver 7","Print Gum MAP N ...

What is the best way to apply multiple conditions to filter JSON data in Flutter?

Hey there, I am looking to enhance the filtering of a JSON list in Flutter by adding an additional condition. Here is a snippet of my JSON structure: { "product": "butox 50 ml", "agencies": [ { ...

The functionality of Vue is acting up with the HTML, unexpectedly refreshing when a button is clicked

I am currently experiencing an issue with my Vue application. When I click the button, it clears the input field (which it shouldn't) and doesn't perform any other actions. The variables "codigo" and "payload" do not display anything on the scree ...

creating a JSON object in PHP that can be easily parsed by JavaScript

In my project, I have an extensive list of items, each item further divided into four sub-items. While it's convenient for me to organize this data in nested arrays using PHP, I encounter issues when trying to transfer them as a JSON object to the cli ...

There is an issue with the function of elem.autocomplete - it is not recognized

I'm new to Angular.JS and have been struggling for the past 6 hours. I've been working on reading data from an HTTP source and displaying it as an autocomplete feature on the view. Previously, the data was displayed in a select box, but I decide ...

Getting the selected value from a dropdown menu in ReactJS

I am working on creating a form that resembles the following structure: var BasicTaskForm = React.createClass({ getInitialState: function() { return { taskName: '', description: '', emp ...