Draw a circle on an image with Javascript

Asked

Viewed 951 times

0

I have an image and when I click on this image, I want to mark with a circle the place where I clicked.

I also need to take the position to record later in the bank, because when I open the image again, I need to draw the circle again in the same position.

It will always be the same image, with the same size, I need to do this in Javascript.I appreciate the attention already.

2 answers

3

From what I understand, that’s what you wanted?

jQuery(document).ready(function(){
    $('#special').attr('height', $('#special').css('height'));
    $('#special').attr('width', $('#special').css('width'));
    
    $("#special").click(function(e){ 

        var x = e.pageX - this.offsetLeft;
        var y = e.pageY - this.offsetTop; 

        /* var c=document.getElementById("special"); */
        var ctx= this.getContext("2d"); /*c.getContext("2d");*/
        ctx.beginPath();
        ctx.arc(x, y, 10,0, 2*Math.PI);
        ctx.stroke();

        $('#status2').html(x +', '+ y); 
   });
})  
#special {
    width: 500px;
    height: 500px;
    border:1px ridge green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body> 
    <h2 id="status2">0, 0</h2>
    <canvas id="special">Not supported</canvas>
</body>

The same code in Jsfiddle

  • Whenever you want to show the code in Javascript to run consider using the Live Snippet Stackoverflow as I did in editing, which makes it practical to see the solution, just as it ceases to depend on external sites.

  • It’s still not exactly what I need. Although the code didn’t go wrong, the circle didn’t appear on the canvas. But I think this is a detail. What I need is for an image to appear on the canvas, and when I click, a ciruclo will appear on the image, in the position I clicked.

2

You can use the library D3.js, take this example:

// Define as variáveis

// Campos para armazenar a posição
let posX = document.querySelector('#posX');
let posY = document.querySelector('#posY');

// Seleciona o elemento SVG e armazena na variável sua altura e largura
let svg = d3.select("svg"),
    width = +svg.attr("width"),
    height = +svg.attr("height"),
// Define o tamanho do circulo
    radius = 20;

// URL da imagem de fundo
let src = 'https://i2.wp.com/cafeinacodificada.com.br/wp-content/uploads/2016/03/61_B.jpg?resize=600%2C320';
// Cria um elemento image e define sua URL
svg.append("image").attr("xlink:href", src);

// Armazena as posições do Circulos criados
let data = [];

let xScale = d3.scaleLinear()
    .domain([0, d3.max(data, function(d) {
        return d.x_pos
    })]).range([0, width]);

svg.selectAll("circle") // Atualiza
    .data(data)
    .enter().append("circle")
    .attr("cx", function(d) {
        return d.x;
    })
    .attr("cy", function(d) {
        return d.y;
    })
    .attr("r", radius)
    .style("fill", "lightblue")
    .attr('id', function(d, i) {
        return 'rect_' + i;
    })
    .on("click", removerCirculo);

// Define o evento Click no elemento SVG
svg.on("click", function() {
    let coords = d3.mouse(this);
    // Armazena a cordenada do click
    let pos = {
        x: d3.event.x,
        y: d3.event.y
    };
    posX.value = 'Posição X: ' + pos.x + '';
    posY.value = 'Posição Y: ' + pos.y + '';

    // Como vai trabalhar apenas com um circulo
    data = []; // Reseta
    svg.selectAll('circle').remove(); // Remove todos os circulos
    
    data.push(pos); // Após resetar e remover todos os circulos, diciona um novo
    
    svg.selectAll("circle") // Atualiza
    .data(data)
    .enter()
    .append("circle")
    .attr("cx", function(d) {
        return d.x;
    })
    .attr("cy", function(d) {
        return d.y;
    })
    .attr("r", radius)
    .attr('id', function(d, i) {
        return 'circulo_' + i;
    })
    .on("click", removerCirculo);
})

function removerCirculo(d) {
    d3.event.stopPropagation();
    data = data.filter(function(e){
        return e != d;
    });
    d3.select(this).remove(); // Remove o circulo que recebeu o click
    posX.value = 'Circulo removido';
    posY.value = 'Circulo removido';
}
circle {
  fill: red; /* cor do fundo */
}
<!-- IMPORTA A BIBLIOTECA D3.js -->
<script src="//d3js.org/d3.v4.min.js"></script>

<!-- O TAMANHO DEFINIDO AQUI, FOI O MESMO DA IMAGEM -->
<svg width="450" height="271"></svg>
<!-- CAMPOS PARA ARMAZENAR A POSIÇÃO -->
<p><input type="text" id="posX" /></p>
<p><input type="text" id="posY" /></p>

To learn more, simply access repository in the Github, has the Gallery of Examples and documentation in English, the translation is outdated, but you can find in Github user’s Jean Bauer.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.