After creating a new canvas, the HTML5 canvas does not appear on the screen

Greetings! I am a newcomer to this forum, but I have utilized it for answers in the past. Currently, I am working on a school project that involves using HTML5, CSS, and JS to create teaching lessons. My approach includes utilizing canvas to develop interactive tools. However, I am facing an issue wherein I have multiple panels with distinct content. One panel employs canvas to display images and information successfully, while attempting to add another canvas to a different panel results in nothing being displayed. Although removing the old canvas code allows the new canvas code to appear, I seek a way to have them both visible concurrently. Any assistance in resolving this matter would be greatly appreciated as I need to make progress on this project for school. Apologies if my explanation is unclear, English is not my first language. Below is a snippet of the code for reference:

<div class="panel">
<!DOCTYPE HTML>
<html>
<head>
<style>
body {
margin: 0px;
padding: 0px;
}
#myCanvas {
border: 1px solid #9C9898;
}
</style>
<script>
window.onload = function() {
var canvas = document.getElementById("h1Canvas");
var context = canvas.getContext("2d");

context.moveTo(100, 150);
context.lineTo(450, 50);
context.lineWidth = 10;

// set line color
context.strokeStyle = "#ff0000";
context.stroke();
};

</script>
</head>
<body>
<canvas id="h1Canvas" width="578" height="200"></canvas>
</body>
</html>


</div>

<div class="panel">
  <!DOCTYPE HTML>
<html>
<head>
<style>
body {
margin: 0px;
padding: 0px;
}
#myCanvas {
border: 1px solid #9C9898;
}
</style>
<script>
window.onload = function() {
var canvas = document.getElementById("myCanvas");
var context = canvas.getContext("2d");

context.moveTo(100, 150);
context.lineTo(450, 50);
context.lineWidth = 10;

// set line color
context.strokeStyle = "#ff0000";
context.stroke();
};

</script>
</head>
<body>
<canvas id="myCanvas" width="578" height="200"></canvas>
</body>
</html>
</div>

In summary, the contents of the first panel are not displaying, whereas the second panel appears correctly. Removing the canvas from the second panel enables the first panel's content to show up.

<div class="panel">


<head>
<style>
body {
margin: 0px;
padding: 0px;
}
#myCanvas {
border: 1px solid #9C9898;
}
</style>
<script>
window.onload = function() {
var canvas = document.getElementById("myCanvas");
var context = canvas.getContext("2d");

context.moveTo(100, 150);
context.lineTo(450, 50);
context.lineWidth = 10;
context.strokeStyle = "#ff0000";
context.stroke();
};

</script>
</head>
<body>
<div><canvas id="myCanvas" width="578" height="200"></canvas></div>
</body>


</div>


<div class="panel">

<head>
<style>
body {
margin: 0px;
padding: 0px;
}
#myCanvas {
border: 1px solid #9C9898;
}
</style>
<script>
window.onload = function() {
var h1canvas = document.getElementById("h1Canvas");
var cntxt = h1canvas.getContext("2d");

cntxt.moveTo(100, 150);
cntxt.lineTo(450, 50);
cntxt.lineWidth = 10;
cntxt.strokeStyle = "#ff0000";
cntxt.stroke();
};

</script>
</head>
<body>
<div><canvas id="h1Canvas" width="578" height="200"></canvas></div>
</body>

</div>

The canvases are placed in different divs due to each div representing a unique panel within a carousel, requiring separate placement rather than combining them on one page.

Answer №1

The correct HTML structure should look something like this:

<!DOCTYPE html>
<html>
    <head>
        <!-- Include your CSS and JavaScript files here -->
    </head>
    <body>
        <!-- Add your HTML elements within the body tag -->
    </body>
</html>

Answer №2

Aside from the questionable structure, there are two canvases in your code both referenced by the variable 'canvas' and two contexts referenced by the variable 'context'. This means you actually only have one canvas and one context.

UPDATE: I have cleaned up your code and adjusted the coordinates in the second canvas to avoid overlapping drawings. Feel free to modify the coordinates as needed.

<!DOCTYPE HTML>
<html>
<head>
<style>
body {
margin: 0px;
padding: 0px;
}
#h1Canvas {
border: 1px solid #9C9898;
}
#myCanvas {
border: 1px solid #9C9898;
}
</style>
<script>
window.onload = function() {
var hcanvas = document.getElementById("h1canvas");
var hcontext = hcanvas.getcontext("2d");

hcontext.moveTo(100, 150);
hcontext.lineTo(450, 50);
hcontext.lineWidth = 10;

// set line color
hcontext.strokeStyle = "#ff0000";
hcontext.stroke();


var mcanvas = document.getElementById("myCanvas");
var mcontext = mcanvas.getContext("2d");

mcontext.moveTo(200, 250); //add 100 to coordinates so that two drawings do not lie on top of each other change as needed
mcontext.lineTo(550, 150);
mcontext.lineWidth = 10;

// set line color
mcontext.strokeStyle = "#ff0000";
mcontext.stroke();
};
</script>
</head>
<body>
<canvas id="h1Canvas" width="578" height="200"></canvas>
<canvas id="myCanvas" width="578" height="200"></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

Explore how Next.js's getServerSideProps feature incorporates loading animations and improves

I have implemented getServerSideProps in my project's pages/post/index.js file: import React from "react"; import Layout from "../../components/Layout"; function Post({ post }) { console.log("in render", post); return ( <Layout title={pos ...

Looking to update table content dynamically using jQuery ajax?

I need assistance in creating a dynamic table that can update its content based on the company selected from a dropdown menu. The data should be fetched using AJAX and only display information related to the chosen company. Furthermore, I would like to imp ...

Recursive function: the process of storing numerous values in variables

There is a code snippet showcasing a recursive function designed to take a number, for example n=5, and produce an array counting down from n to 1 (i.e., [5,4,3,2,1]). The point of confusion arises just before the numbers/values of n are added to countArr ...

The :empty selector is failing to function properly in @media print queries

Currently, I am working in Twig on Symphony and have encountered an issue with an empty div that needs to be hidden in print mode. <div class="form-fields__list"> </div> Surprisingly, the :empty selector works perfectly fine on the screen, bu ...

Issue with Inline JS not functioning correctly in Flask when integrated with Bootstrap 5

I'm developing a Flask web app with Bootstrap 5 and attempting to incorporate inline JS, but it's not functioning as expected. Specifically, I'm trying to use a simple alert() component, but nothing is displaying on the page. Interestingly ...

Displaying a Variety of Images using React and HTML

I've encountered an issue with rendering images that have large file sizes. Whenever I try to upload and display multiple large image files, the performance becomes extremely slow. So my question is: Should the backend handle providing a URL for ver ...

Tips for iterating through an array of images and displaying them in a React component

I am working on a project in my react app where I have 5 images that I want to cycle through indefinitely. The goal is to create an animation where a light bar appears to be constantly moving. https://i.sstatic.net/8tdfV.png The shifting dot in each imag ...

Only one div is revealed by Jquery show and hide, while the other remains hidden

I'm attempting to utilize a single href link to toggle the visibility of two other divs. The first div should be visible by default, while the second div remains hidden. <a href="#ben1" class="fa fa fa-times closer" > <p> clickab ...

Flow of logic for AngularJS ns-show

Being a newcomer to angularjs, I am exploring ways to display an html element based on a property of the $scope object without utilizing any form element. Here is the code snippet: <div id="ListApp"> <div ng-controller="ListCtrl"> ...

JavaScript can be utilized to manage the exit events

Possible Duplicate: Alert when browser window closed accidentally Is there a way to trigger a new window to open when a user clicks the exit button (X) on the browser, similar to how the Wordpress Admin Panel functions? In the Wordpress panel, when t ...

Tips on transmitting and receiving substantial JSON information

As a newbie in the full-stack development world, I am currently on a quest to find an efficient method for transmitting and retrieving large data between my React front-end and Express back-end while keeping memory usage to a minimum. My project involves b ...

Creating color blends in CSS using overlapping layers

In my HTML structure, I have a div with the class "box" and I have utilized pseudo-classes :after to create a blue border around the box and :before to overlay an orange-colored box as shown in the image. I've achieved everything in the image - the bo ...

The most secure method for retrieving User Id in AngularFire2

I'm currently facing a dilemma in determining the most secure method to obtain an authenticated user's uid using AngularFire2. There seem to be two viable approaches available, but I am uncertain about which one offers the best security measures ...

Creating an AJAX request in Knockout.js

Forgive me if this question has been asked previously, as my search attempts have been unsuccessful in finding a solution. Despite consulting the knockout documentation, I still struggle to articulate my issue effectively for searching. My situation invol ...

increase the count by one every second using setInterval

I need my sHand to increase by 6 every second, but currently it only increases once. When I try something like this.sHand++, it works fine and increases by 1 degree per second. However, I want it to increase by 6 instead of 1. Any solutions? data:{ ...

Ways to move upward from a lower position

I am trying to create a hover effect where the title and content move to the right position upon hovering. The issue I am facing is that the transition on the `Title` class is not working, and as a result, the hover effect is also not functioning properly ...

What is an html5 tooltip widget?

I stumbled upon a helpful tutorial on html5canvastutorials.com that caught my eye: let triangle = new Kinetic.Shape(function(){ let ctx = this.getContext(); ctx.beginPath(); ctx.lineWidth = 4; ...

Oops! An issue occurred at ./node_modules/web3-eth-contract/node_modules/web3-providers-http/lib/index.js:26:0 where a module cannot be located. The module in question is 'http'

I have been troubleshooting an issue with Next.js The error I am encountering => error - ./node_modules/web3-eth-contract/node_modules/web3-providers-http/lib/index.js:26:0 Module not found: Can't resolve 'http' Import trace for req ...

What is the best way to denote arrays in ember-data models?

When dealing with an array in a model, is it essential to use DS.hasMany pointing to a DS.Model, even if the array elements are not actual models with IDs or endpoints? Is there a more efficient alternative? Despite using DS.hasMany with { embedded: true ...

mention a numerical value/heading within a JSON list

I encountered an issue while searching through a JSON array filled with Google fonts. The fonts are structured by family -> files -> filename. However, I noticed that sometimes the filename is saved as a number. For example (refer to the bottom of th ...