Create rectangles on a canvas by parsing data from a JSON file

Hey there! I've been working with HTML5 canvas and I need some help drawing rectangles dynamically. Currently, I can draw on the canvas but I want to make it more flexible.

x, y: These represent the coordinates of where the rectangle should be positioned on the canvas.
w: Indicates the width of the rectangle.
h: Denotes the height of the rectangle.
f: If set to true, the rectangle will be filled without a border. If set to false, the rectangle will have a border but no filling.

var canvas = document.getElementById("c");
var context = canvas.getContext("2d");
var json = [{
    "x": "50",
    "y": "50",
    "w": "100",
    "h": "50",
    "f": "true"
  },
  {
    "x": "50",
    "y": "150",
    "w": "100",
    "h": "50",
    "f": "false"
  }
];

context.beginPath();
for (var i in json) {
  context.lineTo(json[i].x, json[i].y, json[i].w, json[i].h, json[i].f)
}
<canvas id="c"></canvas>

Answer №1

Instead of trying to draw rectangles on your canvas, it would be more efficient to utilize the strokeRect() and fillRect() methods.

Take note that the value of your f property will determine which method is called. I recommend converting the value of the f property to a boolean instead of keeping it as a string.

var canvas = document.getElementById("c");
var context = canvas.getContext("2d");
var json = [{x: "50", y: "50", w: "100", h: "50", f: "true" }, { x: "50", y: "150", w: "100", h: "50", f: "false" }];

context.canvas.width = 200;
context.canvas.height = 250;

json.forEach(shape => {
  context[shape.f === 'true' ? 'fillRect' : 'strokeRect'](shape.x, shape.y, shape.w, shape.h);
});
<canvas id="c"></canvas>

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

Having trouble with my React App compiling media files

I'm currently working with create-react-app and using a Data.js file where I define objects with properties that are spread as props in a tag. However, when I run npm start or deploy my application, the image doesn't show up. It seems like the co ...

Implementing Facebook Javascript SDK to enable login and trigger re-authentication using React Web and Typescript within a component

As a newcomer to stack overflow, I welcome any suggestions on how I can improve my question. I'm in need of guidance concerning logging a user into facebook and requiring them to authenticate their profile or select another profile manually, rather t ...

Another return payload failing to retrieve the return value

I'm currently facing an issue where a function that should return a value is not being passed on to another function. Below is the code snippet in question: public _getProfileToUpdate() { return { corporateId: this.storeService.setStoreData().p ...

Application built using the MEAN stack and Java technologies

Having worked as a Java/J2EE developer for several years, I have found that my learning has stagnated due to the nature of my daily job and company. To address this issue, I have decided to embark on my own personal project with the following key details/ ...

"Exploring the use of jQuery to access dynamic CSS properties such as :before and implementing filter

I am facing an issue with jQuery and CSS. Below is the code snippet: $("#test").append($("<div>",{ style:"width:48%; margin-left:1%; margin-right:1%; margin-bottom:10px; float:left; background-image:url(http://test.png); filter:brigh ...

What is the method to execute jQuery code after the completion of a fade out effect?

I am attempting to fade out a div upon click while also adjusting some CSS properties. The problem I am encountering is that the CSS properties change during the fade out transition, instead of after it has completed. I would like the values to change onc ...

JavaScript's local storage feature seems to be failing in both saving and retrieving data

I'm working on a fun math game where two random numbers and a sign (+ or -) are generated using Math.random(). The user needs to input their answer in the provided input box. However, I am facing an issue with saving and retrieving the score and high ...

Navigating to a new URL after submitting a form in React

Hello, I am new to React and have created a form that successfully sends data to Firebase. However, after submitting the form, I would like to redirect to /thankyou.html which is outside of the React app. Can someone please guide me on how to achieve this ...

What are some solutions for resolving JavaScript's 'undefined' error?

(function(window) { var johnGreeter = {}; johnGreeter.name = "John"; var greeting = "Hello "; johnGreeter.sayHello = function() { console.log(greeting + johnGreeter.name); } window.johnGreeter = johnGreeter; })(window); // <!DOCTYPE html ...

Determine the absent information by comparing two JSON objects with JavaScript

Two JSON objects, counties and ctyIndem, are at hand. The counties object contains all the counties in a specific US State, while ctyIndem holds information about indemnities paid in that State by county, excluding those with no payments made. My task is t ...

How do I invoke a function from within a content page in AngularJS within the Ionic Framework?

Greetings! I am new to Angular and Ionic, eager to enhance my skills through hands-on learning. In my controllers file, I have a controller set up like this: Additionally, all my content pages are linked to this controller. The structure of the content is ...

Stop automatic image sliding by hovering in jQuery

How can I make the image slider pause on hover? Here is the code that I have been using: $(".col-md-8").hover(function() { clearTimeout(timer); }); It seems like this should work, but for some reason it's not. Can anyone ...

Encountering the error "Cannot GET /login" while attempting to send a file through a post request in Express.js

I'm having trouble sending a new HTML file to the user after a successful login. Every time I attempt to send the file, I keep getting an error message saying "Cannot GET /login" on the page. Below is the section of code that's causing me diffic ...

Executing multiple requests simultaneously with varying identifiers following a waiting period

I am looking to send a GET request using the user_id key retrieved from the userData object. This is how the request should be structured: Let's assume we have userData defined as follows: var userData = [ { id: 1, user_id: ...

Enhancing HTML Vue JS by Dynamically Adding Rows Based on Multiple Selections

<div id="addForm"> <div class="row"> <div class="col-md-4"> <div class="form-group label-floating"> <label class="control-label">Case Type</label> <select class="form-control" v-mo ...

A guide on dynamically using jQuery to embed an image within a hyperlink tag

I am having trouble with these HTML tags: img = <img data-dz-thumbnail="" target="_blank" alt="twitter-btn-mob.png" src="image.jpg"> a = <a href="javascript:void(0)" target="_blank"></a> My goal is to insert the image tag into the anc ...

Guide to building a React project with an outdated edition of Create React App

Currently, I'm following an older tutorial to learn React, and as a result, I need to set up a project using Create React App version 1.5.2. I successfully installed <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="204352454 ...

How to Retrieve Video Length using AJAX in the YouTube API

I have been working on a script to fetch the duration of a YouTube video using its id. Here is the code snippet I've written: var vidID = ""; var vidData; var vidDuration; function getResponse() { $.getJSON( "https://www.googleapis.c ...

The value of a variable fails to update when attempting to increment it with the useState hook

My variable is initially set up like this: let [count_farmers, set_count_farmers] = useState(0); My goal is to increment the variable when a user registers on my page. Here's what I'm trying to do: let handleAddUser = (userinfo) => { ...

Cross domain widget ajax request

Our company offers a widget for clients to add to their websites. This widget requires a call to our website to validate user-entered data. However, due to domain restrictions, making ajax calls from the client's website to ours is not permitted. Is ...