Using Various Interactive Canvases with HTML5

I am currently working on a website project that requires multiple canvases to encircle individual images.

After experimenting with HTML, CSS, and JS on JSfiddle, I successfully achieved the desired effect with a single image. However, when I duplicated the HTML code, the second canvas was not created (or perhaps it overlapped with the first one?)

Link to the JSfiddle

How can I modify the code so that each image has its own corresponding canvas?

  var canvas = document.getElementById('border');
      var context = canvas.getContext('2d');
      var x = 58;
      var y = 58;
      var radius = 55;
      var startAngle = 1.5 * Math.PI;
      var endAngle = 1 * Math.PI;
      var counterClockwise = false;

      context.beginPath();
      context.arc(x, y, radius, 0, 2 * Math.PI, false);
      context.lineWidth = 3;

      // line color
      context.strokeStyle = '#ebebeb';
      context.stroke();
      
      context.beginPath();
      context.arc(x, y, radius, startAngle, endAngle, counterClockwise);
      
      context.lineWidth = 4;
      context.strokeStyle = '#8aff92';
      context.stroke();
.pkmn 
{
position: relative;
  display: inline-block;
  margin: 5px;
  width: 116px;
  height: 116px;
}

.pkmn .sprite
{
padding: 5px;
position: relative;
    top: 5px;
    left: 5px;
    z-index: -1;
}

// Remaining CSS styles skipped for brevity

<div class="pkmn">
    <canvas id="border" class="exp" width="115" height="115"></canvas>

    <div class="lvl">95</div>
    
    <img alt="test" src="http://cdn.bulbagarden.net/upload/7/76/Spr_5b_143_s.png" class="sprite">
    <img alt="item" src="http://cdn.bulbagarden.net/upload/0/0f/Bag_Leftovers_Sprite.png" class="item">
    <img alt="crown" src="http://cdn.bulbagarden.net/upload/c/c5/Leaf_Crown_Sprite.png" class="crown">
    <img alt="star" src="http://cdn.bulbagarden.net/upload/2/27/ShinyVIStar.png" class="star">
    <img alt="heart" src="http://i1055.photobucket.com/albums/s519/impojr/heart_zpsdaihll9m.png" class="heart">
</div>

// Second set of HTML elements for another image and canvas

Answer №1

Attention: Quirky Mode Warning!

Avoid using duplicate ID's as this can significantly slow down your page and lead to unexpected behavior when the browser switches to quirks mode.

I am providing this answer to emphasize the importance of this issue, especially since the existing answer contains another problematic piece of code.

for (var i = 0; i < document.querySelectorAll('.border').length; i++) {  
      var canvas = document.querySelectorAll('#border')[i];

The above code performs two separate document queries for each item found by the query, which could drastically impact the performance of your page on lower-end devices with just a few matching elements.

const canvases = document.querySelectorAll('.exp')
for (var i = 0; i < canvases.length; i++) { 
      var canvas = canvases[i];
      var context = canvas.getContext('2d');
      var x = 58;
      var y = 58;
      var radius = 55;
      var startAngle = 1.5 * Math.PI;
      var endAngle = 1 * Math.PI;
      var counterClockwise = false;

      context.beginPath();
      context.arc(x, y, radius, 0, 2 * Math.PI, false);
      context.lineWidth = 3;

      // line color
      context.strokeStyle = '#ebebeb';
      context.stroke();
      
      context.beginPath();
      context.arc(x, y, radius, startAngle, endAngle, counterClockwise);
      
      context.lineWidth = 4;
      context.strokeStyle = '#8aff92';
      context.stroke();
}
.pkmn 
{
position: relative;
  display: inline-block;
  margin: 5px;
  width: 116px;
  height: 116px;
}

.pkmn .sprite
{
padding: 5px;
position: relative;
    top: 5px;
    left: 5px;
    z-index: -1;
}

/* More CSS styling rules go here */

<div class="pkmn">
    <canvas id="border1" class="exp" width="115" height="115"></canvas>

    <div class="lvl">95</div>
    
    <img alt="test" src="http://example.com/image.png" class="sprite">
    <img alt="item" src="http://example.com/item.png" class="item">
    <img alt="crown" src="http://example.com/crown.png" class="crown">
    <img alt="star" src="http://example.com/star.png" class="star">
    <img alt="heart" src="http://example.com/heart.png" class="heart">
</div>

<div class="pkmn">
    <canvas id="border2" class="exp" width="115" height="115"></canvas>

    <div class="lvl">95</div>
    
    <img alt="test" src="http://example.com/image.png" class="sprite">
    <img alt="item" src="http://example.com/item.png" class="item">
    <img alt="crown" src="http://example.com/crown.png" class="crown">
    <img alt="star" src="http://example.com/star.png" class="star">
    <img alt="heart" src="http://example.com/heart.png" class="heart">
</div>

Answer №2

Implement a for loop to iterate through all elements with the id "border". Here is the updated code:

for (var i = 0; i < document.querySelectorAll('#border').length; i++) { 
      var canvas = document.querySelectorAll('#border')[i];
      var context = canvas.getContext('2d');
      var x = 58;
      var y = 58;
      var radius = 55;
      var startAngle = 1.5 * Math.PI;
      var endAngle = 1 * Math.PI;
      var counterClockwise = false;

      context.beginPath();
      context.arc(x, y, radius, 0, 2 * Math.PI, false);
      context.lineWidth = 3;

      // line color
      context.strokeStyle = '#ebebeb';
      context.stroke();
      
      context.beginPath();
      context.arc(x, y, radius, startAngle, endAngle, counterClockwise);
      
      context.lineWidth = 4;
      context.strokeStyle = '#8aff92';
      context.stroke();
}
.pkmn 
{
position: relative;
  display: inline-block;
  margin: 5px;
  width: 116px;
  height: 116px;
}

.pkmn .sprite
{
padding: 5px;
position: relative;
    top: 5px;
    left: 5px;
    z-index: -1;
}

.pkmn .lvl
{
font-family: 'Courier New Regular', sans-serif;
font-size: 30px;
z-index: 100;
position: absolute;
    margin-top:0;
}

.pkmn .crown
{
  position: absolute;
  left: 44px;
  bottom: 9px;
}

.pkmn .item
{
  position: absolute;
  left: 10px;
  bottom: 12px;
}

.pkmn .star
{
  position: absolute;
  right: 30px;
  top: 14px;
}

.pkmn .heart {
  position: absolute;
  right: 10px;
  top: 40px;
}

.pkmn .exp {
  position: absolute;
  display: inline-block;
}
<div class="pkmn">
    <canvas id="border" class="exp" width="115" height="115"></canvas>

    <div class="lvl">95</div>
    
    <img alt="test" src="http://cdn.bulbagarden.net/upload/7/76/Spr_5b_143_s.png" class="sprite">
    <img alt="item" src="http://cdn.bulbagarden.net/upload/0/0f/Bag_Leftovers_Sprite.png" class="item">
    <img alt="crown" src="http://cdn.bulbagarden.net/upload/c/c5/Leaf_Crown_Sprite.png" class="crown">
    <img alt="star" src="http://cdn.bulbagarden.net/upload/2/27/ShinyVIStar.png" class="star">
    <img alt="heart" src="http://i1055.photobucket.com/albums/s519/impojr/heart_zpsdaihll9m.png" class="heart">
</div>

<div class="pkmn">
    <canvas id="border" class="exp" width="115" height="115"></canvas>

    <div class="lvl">95</div>
    
    <img alt="test" src="http://cdn.bulbagarden.net/upload/7/76/Spr_5b_143_s.png" class="sprite">
    <img alt="item" src="http://cdn.bulbagarden.net/upload/0/0f/Bag_Leftovers_Sprite.png" class="item">
    <img alt="crown" src="http://cdn.bulbagarden.net/upload/c/c5/Leaf_Crown_Sprite.png" class="crown">
    <img alt="star" src="http://cdn.bulbagarden.net/upload/2/27/ShinyVIStar.png" class="star">
    <img alt="heart" src="http://i1055.photobucket.com/albums/s519/impojr/heart_zpsdaihll9m.png" class="heart">
</div>

Retrieve all elements with the id "border" using document.querySelectorAll().

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

CSS - Display property not behaving as expected with an image tag

Having trouble displaying a speech bubble on my page. I created it using a div for the content and an image for the tail, both of which are hidden when the page loads. When a specific button is clicked, they are supposed to be displayed. However, only the ...

AFRAME - Enhanced scene overlay

I am currently exploring ways to implement an overlay menu on top of an A-FRAME scene. A great example of what I am aiming for can be found on this website -> By clicking on one of the tiles in the home menu, you will see that the previous scene is mo ...

Ways to transfer a jQuery variable value to a PHP variable

I am trying to transfer a jQuery variable value to a PHP variable on the same page using AJAX in my JavaScript code. I have attempted to print the PHP variable but encountered an error. Any assistance would be greatly appreciated. <script type="text/ ...

Issue with MaterialUI value prop not updating after dynamic rendering of components when value state changes

As I dynamically generate Material UI form components, I encounter an issue with updating their values. The value prop is assigned to a useState values object, and when I update this object and the state, the value in the object changes correctly but the M ...

Display data fetched from concurrent Ajax calls in a React Component

I am currently in the process of converting my original project to Reactjs. Since I am new to this and it's my first application, I could use some guidance on how to effectively implement this in a React-friendly way and enhance both my skills and the ...

Tips for delaying a node api's execution until a database query no longer returns null

While it may seem like an unnecessary complication, in my current scenario, it is exactly what I require. I am dealing with an API (API-1) that communicates with a third-party service. Instead of directly providing me with a response that I can send back ...

Guide to using JavaScript to populate the dropdown list in ASP

On my aspx page, I have an ASP list box that I need to manually populate using external JavaScript. How can I access the list box in JavaScript without using jQuery? I am adding the JavaScript to the aspx page dynamically and not using any include or impor ...

Why isn't the card positioned in the center of the screen?

Why is the card not centered on the screen as it is supposed to be? I am utilizing Bootstrap 4.5 <div class="container"> <div class="row"> <div class"col"></div> <div class="col-8"> <div class="card"> ...

Issues with the collapsed navigation button not functioning properly on mobile devices with a Twitter Bootstrap layout

Encountering a problem where the collapsible navigation menu button is unresponsive on mobile browsers, while functioning correctly on desktop. I suspect it may be related to the parallax script installed by my client. Check out the page here: http://21 ...

Is it necessary to integrate the Facebook JavaScript SDK even if I do not plan on utilizing its features?

I have created some simple applications to use as custom tabs on my Facebook page, consisting of hyperlink images. I am not utilizing any of the functionality provided by the Facebook JavaScript SDK in these instances. Do I really need to load the Faceboo ...

What makes table layouts load pages more quickly?

Is it true that Google uses tables for layout because they load faster? I'm skeptical of this claim, as a CSS based layout with minimal and semantic markup seems like it would be more efficient in terms of page load time. It is commonly believed that ...

Row in Bootstrap 3 fails to display correctly on medium-sized devices

Having trouble with divs of different sizes? I want a row that shows 3-column wide divs on medium & large screens and 6-column wide divs on small devices. <div class="container"> <div class="row"> <div class="service col-sm-6 col-md-3"& ...

Troubleshooting GLSL scripts within a web-based WebGL environment

Are there ways to debug GLSL code or display variable values directly from within the GLSL code when using it with WebGL? Does three.js or scene.js offer any features for this purpose? ...

Eliminate the initial padding in an everlasting horizontal CSS animation

Is there a way to start an infinite horizontal animation inside the screen instead of outside and then bring it in? I have successfully implemented the animation, but it currently starts off-screen. .marquee { margin: 0 auto; white-space: nowrap ...

"Click to view the latest data visualization using the Chart.js

I am exploring ways to enhance the animations in Chart.js for a new web project. The content is organized in tabs, with the chart displayed on the third tab out of four. Currently, the chart animates upon loading. How can I make it so that when #chartTrig ...

Invoke a function within the React library through ReactDOM.render

Within my index.js file, I have the following code: const store = createStore( combineReducers({ i18n: i18nReducer }), applyMiddleware(thunk) ); syncTranslationWithStore(store) store.dispatch(loadTranslations(translationsObject)); stor ...

Ensure that the width of the inner table matches the width of its contents within an overflowing div

I'm facing an issue with a table inside a div styled as table-wrapper: .table-wrapper { display: inline-block; overflow-x: scroll; width: 800px; } Although I want the div to display a horizontal scrollbar so that the table inside it can ...

State update failing to modify arrays

Shown below is an array that contains boolean values: const [state, setState] = React.useState({ [`${"checkedA"+index}`]: false, [`${"checkedB"+index}`]: false, [`${"checkedC"+index}`]: false, [`${"checkedD"+index}`]: false, }); ...

How can I retrieve the checked values of checkboxes and store them in an array using React?

https://i.sstatic.net/jTRRU.png This toggle button is dynamically generated based on data, and I need to save the checked values in an array. Code {this.state.customersmsselect.map((e, key) => { if(e.isactive == "ON"){ return ( &l ...

Choose a specific field from a Django filter option

Just had a quick query: Is there a way for me to choose only one field from my filter form in Django? At the moment, I'm showcasing the entire form: <div class="container"> <form method="GET" > {{ filter.form.Precio|crispy }} ...