Drawing a circle in a canvas on mouseclick

前端 未结 1 725
野趣味
野趣味 2020-12-18 09:50

I want to draw a filled (or not filled) circle in a canvas on mouseclick, but I can\'t get my code to work properly, I\'ve tried pretty much everything!

This is my H

相关标签:
1条回答
  • 2020-12-18 10:19

    I have forked and updated your fiddle to make a working example: http://jsfiddle.net/ankr/ds9s7/161/

    Besides referencing the event incorrectly - as stated by others - you also did not begin nor end your path when drawing. Added context.beginPath() and context.fill() calls

    Here's the relevant JS code

    var canvas = document.getElementById("imgCanvas");
    var context = canvas.getContext("2d");
    
    function draw(e) {
        var pos = getMousePos(canvas, e);
        posx = pos.x;
        posy = pos.y;
        context.fillStyle = "#000000";
        context.beginPath();
        context.arc(posx, posy, 50, 0, 2*Math.PI);
        context.fill();
    }
    
    function getMousePos(canvas, evt) {
        var rect = canvas.getBoundingClientRect();
        return {
          x: evt.clientX - rect.left,
          y: evt.clientY - rect.top
        };
    }
    
    0 讨论(0)
提交回复
热议问题