Creating dynamic HTML5 canvas elements in ASP.NET

My webpage features multiple canvas elements that dynamically appear based on VB code.

Here's a snippet of my aspx page structure:

<canvas id="canvasnhlrc" width="225" height="200" runat="server"></canvas>
<canvas id="canvascwl" width="225" height="200" runat="server"></canvas>
<canvas id="canvashslanguages" width="225" height="200" runat="server"></canvas>

And here's what my aspx.vb code entails:

canvasnhlrc.Visible = False
canvascwl.Visible = False
canvashslanguages.Visible = False

        If RouteData.Values("mediasubType") IsNot Nothing Then

            Dim qsubMedia As String = RouteData.Values("mediasubType")

            Select Case qsubMedia

                Case "nhlrc"

                    canvasnhlrc.Visible = True

                Case "cwl"

                    canvascwl.Visible = True

                Case "hslanguages"

                    canvashslanguages.Visible = True

            End Select

        End If

For instance, when my page is example.com/nhlrc, the corresponding canvas generated looks like this:

<canvas id="ContentPlaceHolder2_canvasnhlrc" width="225" height="200"></canvas>

To fit this setup, my javascript file is structured as shown below:

function init() 
{ 
    var w1 = document.getElementById('ContentPlaceHolder2_canvasnhlrc')
    var w1x = w1.getContext('2d');
    w1x.shadowOffsetX = 0;
    w1x.shadowOffsetY = 0;
    w1x.shadowBlur = 20;
    w1x.shadowColor = "rgba(0, 0, 0, 0.75)";
    w1x.fillStyle = 'rgb(218, 233, 246)';
    // Drawing commands for w1 canvas...

    var w2 = document.getElementById('ContentPlaceHolder2_canvascwl')
    var w2x = w2.getContext('2d');
    // Similar drawing commands like above...

    var w3 = document.getElementById('ContentPlaceHolder2_canvashslanguages')
    var w3x = w3.getContext('2d');
    // More drawing commands...
}
onload = init;

But I'm facing an issue where only the first canvas element (NHLRC) renders successfully, while the subsequent ones such as example.com/cwl do not display. When I test with each canvas individually, they work fine. What could be causing this conflict preventing all canvas elements from rendering properly?

Answer №1

The init function in your code is currently handling too many tasks - finding, verifying, and drawing elements times three. If any of these tasks fails, such as not being able to find an element, the entire process comes to a halt. Additionally, the variables w1, w2, and w3 are defined only on specific pages, rather than universally across all pages.

A simpler approach would be:

function drawCanvas(canvasElement, fillColor) 
{ 
    var ctx = canvasElement.getContext('2d');
    ctx.shadowOffsetX = 0;
    ctx.shadowOffsetY = 0;
    ctx.shadowBlur = 20;
    ctx.shadowColor = "rgba(0, 0, 0, 0.75)";
    ctx.fillStyle = fillColor;
    ctx.beginPath();
    ctx.moveTo(25, 25);
    ctx.lineTo(175, 25);
    ctx.lineTo(175, 50);
    ctx.lineTo(200, 75);
    ctx.lineTo(175, 100);
    ctx.lineTo(175, 175);
    ctx.lineTo(25, 175);
    ctx.closePath();
    ctx.fill();
}

function initialize()
{
  var canvases = [['ContentPlaceHolder2_canvasnhlrc', 'rgb(218, 233, 246)'],
     ['ContentPlaceHolder2_canvascwl', 'rgb(12, 64, 114)'],
     ['ContentPlaceHolder2_canvashslanguages', 'rgb(12, 64, 114)']];

   for(var i=0; i<canvases.length; i++)
   { 
       var canvas = document.getElementById(canvases[i][0]);
       if (canvas != null) {
         drawCanvas(canvas, canvases[i][1]);
         break;              
       }
   }
}

onload = initialize;

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

How can I make an HTML button the default option within a form?

Currently, I am working on an asp.net page which contains a mix of asp.net buttons and HTML input[type=button] elements. These HTML buttons are specifically used to initiate AJAX calls. My dilemma arises when the user hits ENTER - instead of defaulting to ...

Implementing a method to pass total value to the <td> tag in angular JS using controller

I am having trouble calculating the total IR for each table cell. Despite my efforts, the function is not working as expected and I can't figure out why. $scope.getTotalb = function () { var totalb = 0; for (var i = 0; i < $scope ...

Creating self-referencing MongoDB schema with post routes in nodejs: A step-by-step guide

I am currently working on building a nested parent-child system where the child schema mirrors that of the parent. Below is the schema for the parent, where children refer back to the parentSchema: var mongoose = require("mongoose"); var parentSchema ...

Error occurred while trying to parse JSON due to an abrupt ending

While attempting to reinstall one of my old vue projects on my new computer (running Windows 10) using npm, I encountered the following error: npm ERR! Unexpected end of JSON input while parsing near '...n":"0.8.1","devDepend' ...

Despite having the packages listed in both my package.json file and node_modules folder, I am encountering undefined packages

Currently, I am in the process of building a web application using NestJS for the backend. Docker is playing a crucial role in the development process as I am utilizing it to compile all my backend components. One issue that has arisen is with certain inst ...

My function is named, however, the output is recorded prior to the function completing its execution

I've implemented a function named createUser, designed to save user data in the database. If successful, it should return true; otherwise, false. The code for this function is as follows: exports.createUser = (user) => { const salt = crypto.rando ...

What techniques does Twitter use to insert labels into text boxes?

When I visited the Twitter login page, I noticed something interesting - the labels for input fields were inside the input fields themselves. It seemed to be accomplished using a common trick involving javascript/jquery. Intrigued, I delved into the Twitte ...

Is there a barrier I've reached with the amount of hashtags I'm using?

My goal is to limit the use of javascript and rely more on CSS to achieve desired effects on my website. One feature I have developed is a modal that opens using hashtags and targets, similar to this example: http://codepen.io/maccadb7/pen/nbHEg. While th ...

Issue with SVG animation causing unnecessary duplication of circle shapes when utilizing animateMotion

I have implemented animateMotion to create an animation along a path. Below is the code snippet that demonstrates this: <!DOCTYPE html> <html> <head> <title>Example Of Many Things!</title> </head> <body> ...

How to update ReactJS variables without the need for executing the code

My mind is in a whirlwind... If anyone can shed light on this: componentDidUpdate(prevProps, prevState) { let categoriesChange = false console.log('check', JSON.stringify(this.checkedd), JSON.stringify(this.props.checked)) if (JSON ...

Encountering an undefined json array when making an AJAX request

There have been numerous questions on this topic, but none of the specific solutions seemed to apply to my situation. So, I apologize if this is a duplicate query. I am currently working on fetching data from an SQL database using a PHP file that passes t ...

tsc failing to generate the distribution folder

I've encountered a strange issue with compiling my TypeScript project into the ./bin folder. The tsc command runs without any errors, but nothing is actually being created in the designated folder. It's puzzling me and I can't seem to figure ...

Failing to reach the nested if statements within a switch case block

Before removing my question, please read this. Despite testing with console.logs, my code does not enter the if statements. I have not come across a similar solution to my issue. In an attempt to address any timing or asynchronous problems, I added a use ...

Loading a Redux-Form component from an external file causes the loading process to grind to a

I am encountering an issue where the page freezes for a long time when I try to import a field from an external file. I suspect that the problem lies with component={SurveyField}, because when I change it to component="input", the page loads successfully. ...

When importing a module, the function in the ts file may not be recognized or located

While attempting to create a VSTS (Azure Devops) Extension, I encountered a perplexing issue. Within my HTML page, I have a button element with an onclick listener: <!DOCTYPE html> <head> <script type="text/javascript"> VS ...

What is the best way to access the iframe element?

This is main.html <body> <iframe id="frame" src="frame.html"></iframe> <script type="text/javascript"> document.getElementById('frame').contentWindow.document.getElementById('test').innerHtml = &apos ...

Retrieving multiple checkbox values from the front end using AJAX and passing them to

I have some code for ajax that is causing me issues. Here it is: var userCheckbox = $("input[name=chk]:checked").val(); This is the checkbox section in my html: <input id="checkbx" type="checkbox" name="chk" value="apple"/>apple</td> <inp ...

Ways to accentuate dates on a calendar using a variety of colors based on specific events

Here is the Java script code for my calendar: <script type="text/javascript"> $(function() { var startDate; var endDate; var selectCurrentWeek = function() { window.setTimeout(function () { $('.week-picker' ...

Connection string for MySQL in GCP

Could someone please assist me with connecting to a MySQL 8.0 database on GCP from Heroku? I have hosted my ASP.NET core web API on Heroku and attempted several connection strings, but I am struggling to establish a successful connection. Below are the dif ...

Discovering the final record on a page in Crystal Reports

Is there a way to locate the final record on a page in a crystal report? In my report, I have detail sections A and B. I am interested in hiding detail section B only when the last record on the page is being printed. Appreciate any help! ...