Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

142
Views
Adding a class to an html5 canvas element

I have a rectangle and a star that i have drawn in an html5 canvas. I wanted to give each element a class . How can that be done ?

I have tried

ctx.classList.add('box'); ctx.classList.add('Star');

And it seems that is not the correct approach to it .

I wonder if there is a way to just ass a class name.

<!DOCTYPE html>


<html lang="en">
 <head>
  <meta charset="UTF-8" />
  <title>boxstar</title>
  <script>

    function init() {

      var canvas = document.getElementById("canvas");
      var ctx = canvas.getContext("2d");

      draw(ctx);
    }

    function draw(ctx) {

      ctx.save();
      ctx.beginPath();
      ctx.moveTo(477.6, 312.2);
      ctx.lineTo(49.8, 312.2);
      ctx.lineTo(49.8, 0.0);
      ctx.lineTo(477.6, 0.0);
      ctx.lineTo(477.6, 312.2);
      ctx.closePath();
      ctx.fillStyle = "rgb(248, 15, 15)";
      ctx.fill();

      
      ctx.beginPath();
      ctx.moveTo(448.9, 997.8);
      ctx.lineTo(277.4, 907.7);
      ctx.lineTo(106.0, 997.8);
      ctx.lineTo(138.7, 806.9);
      ctx.lineTo(0.0, 671.7);
      ctx.lineTo(191.7, 643.8);
      ctx.lineTo(277.4, 470.1);
      ctx.lineTo(363.2, 643.8);
      ctx.lineTo(554.9, 671.7);
      ctx.lineTo(416.2, 806.9);
      ctx.lineTo(448.9, 997.8);
      ctx.closePath();
      ctx.fill();
      ctx.restore();
    }
  </script>
 </head>
 <body onload="init()">
   <canvas id="canvas" width="555" height="998"></canvas>
 </body>
</html>

Thanks in advance for your time !

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!