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

What could be causing the issue with receiving deserialized data in my WebAPI?

I have a straightforward WebAPI application. Here is an excerpt from my controller: [HttpPost] public ActionResult DoSomeWork(string stringParam, DTOObject dto) { // Some work happens here } My console application is calling this method as follows: ...

Tips for effectively implementing a curried selector function with the useSelector hook in react-redux

In my project using react-redux with hooks, I encountered a situation where I needed a selector that takes a parameter which is not passed as a prop. Upon checking the documentation, it mentioned: The selector function does not receive an ownProps argum ...

Tips for successfully parsing JSON data during an Ajax call

After making an Ajax call, the response.responseText I receive looks like this: . "[ columns :[ { "id":"name", "header":"User name" }, { "id":"birth", "header":"Date of birth" } ], ...

Displaying a component after retrieving a value from AsyncStorage in a React Native application

I have developed a React Component that saves user settings in the AsyncStorage and retrieves them upon loading. The functionality of storing and retrieving data is working fine, but I am facing an issue where the component renders before the values are ...

Importing JavaScript into an Angular component: A beginner's guide

Within my Angular-11 project, I have included the following JavaScript file: "node_modules/admin-lte/plugins/bs-stepper/js/bs-stepper.min.js", I have added it to the angular.json configuration as detailed above. import Stepper from '.. ...

Vuejs v-for nested loops

After spending countless hours researching, I am determined to solve this problem. My objective is to create a questionnaire similar to a Google Form, with question groups, questions, and answers. The structure of my data looks like this: question_group: ...

Prevent the submit button from being clicked again after processing PHP code and submitting the form (Using AJAX for

I've set up a voting form with submit buttons on a webpage. The form and PHP code work fine, and each time someone clicks the vote button for a specific option, it gets counted by 1. However, the issue is that users can spam the buttons since there i ...

Plaid webhook failing to activate

I've been struggling to set up Plaid transaction webhooks in an api, as I can't seem to get any webhooks to trigger. I followed the plaid quickstart code and included the webhook parameter: Plaid.create({ apiVersion: "v2", clientName: ...

Troubleshooting JSON PHP problems when writing to a database

Below is the code found in RadarsMySql.php: <?php $con = mysql_connect("localhost","root","dacian"); $db = mysql_select_db("radars"); $sql = mysql_query("SELECT latitude,longitude,description FROM radars WHERE id > '0'"); while($ro ...

Is there a way to transform an HTMLCollection into an array without depleting it of its elements?

I've been attempting to transform a collection of 4 divs in HTML into an array, but all my efforts seem to lead to the array becoming void. <div class="container"> <div class="shape" id="one"></div> <div class="sh ...

Creating and adding nested div elements with the power of JavaScript

My goal is to utilize JavaScript for updating the CSS layout as the webpage loads. Below is the code I have been working on: var container = 0; // Total UI Container var containerTitle = 0; // Title Container var article = 0; var articleTitle = 0; var ...

What is the best way to transform a JSON array in text format into a JSON object array using NodeJS or JavaScript?

I have a RESTful API built with Node.JS and ExpressJS. I want to retrieve a JSON array from the FrontEnd and pass it into my API. api.post('/save_pg13_app_list', function (req, res) { var app_list = { list_object: req.body.li ...

Display issue with JSON data on widget

I am in the process of developing a widget that will retrieve weather information from a website offering JSON services and display it. Below is the code snippet: Widget: public class MainActivity extends AppWidgetProvider { public static void onUpdat ...

Just encountered an issue stating "PrismaClient cannot run in the browser" while working with [Next.js]

My initial plan was to log all the IDs of news in my database using console. However, when I executed the code, an error occurred as shown in this image. What is the best way to address and resolve this issue? https://i.stack.imgur.com/ci8G1.png ...

Body-Processing Protocol

When I send a cURL POST request, it looks like this: curl http://tarvos.local:8080/partial_Users/2 -d '{currentPage : 1, firstID : 53d62fc6642aecf45c8b456f }' Within my NodeJS application, the request passes through the bodyParser.json() middl ...

What is the best way to create this server backend route?

I'm currently working on a fullstack project that requires a specific sequence of events to take place: When a user submits an event: A request is sent to the backend server The server then initiates a function for processing This function should ru ...

What is the best way to remove a particular element from an array stored in Local Storage?

Currently working on a web application that features a grade calculator allowing users to add and delete grades, all saved in local storage. However, encountering an issue where attempting to delete a specific grade ends up removing the most recently add ...

Minimize the entire project by compressing the .css, .js, and .html files

After recently incorporating Grunt into my workflow, I was thrilled with how it streamlined the process of minifying/concatenating .css files and minifying/uglify/concatenating .js files. With Grunt watch and express, I was able to automate compiling and ...

Displaying decimal values in Angular as percentages

In my Angular application, I have a numeric textbox that displays a percentage value and allows users to update it. https://i.stack.imgur.com/eCOKe.png <label for="fees">Fees %</label> <div class="inpu ...

Discover the method to retrieve every element from a Listbox with the click of a Button and utilizing an ajax call

How can I retrieve all the elements from a Listbox when a Button Click event triggers an ajax call? I have created a function that successfully returns all the elements from the Listbox. However, when I try to bind it with the ajax call, it doesn't w ...