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

109
Views
Centering interactable canvas in javascript

I have the following code:

    function up(e) {
        if(e.target.id === 'appCanvas') {
            // add circle at cursor coords
        }
    }
    canvas {
       padding: 0;
       margin: auto;
       display: block;
       width: 80%;
       height: 80%;
       position: absolute;
       top: 0;
       bottom: 0;
       left: 0;
       right: 0;
    }
    <html>
    <head>
        <meta charset="utf-8">
        <title>Graphs</title>
        <link rel="stylesheet" href="index.css">
        <script type="module" src="application.js"></script>
    </head>

    <body>
        <div>
            <canvas id="appCanvas" style="border:5px solid #000000;"></canvas>
        </div>
    </body>
    </html>

This creates a html canvas located in the center of the page with a width and height of 80% of the inner page. However, on the javascript side of things, it is not adding a circle at the exact coordinates, it is rather shifted by 20% of the canvas height and width.

How exactly would I make it so I interact with only the 80% canvas, and create circles exactly on the canvas?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

use a click event on the canvas. use clientx and clienty methods from the event to create the circle using the arc function and then display the circle using the stroke/fill function

I got it of w3 schools https://www.w3schools.com/tags/canvas_arc.asp

This is some code I wrote

const canvas = document.querySelector("#appCanvas");

canvas.addEventListener("click", circle);

function circle(e){
var ctx = canvas.getContext('2d');
ctx.arc(e.clientX,e.clientY,2, 0,2*Math.PI);
ctx.stroke(); 
}
about 4 years ago · Juan Pablo Isaza Report
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!