Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

110
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda