Drawing a circle on the canvas using mouse events

前端 未结 1 944
清歌不尽
清歌不尽 2021-01-01 01:36

I am trying to draw a circle using mouse on the canvas using mouse events, but it does not draw anything:

tools.circle = function () {
var tool = this;
this.         


        
1条回答
  •  借酒劲吻你
    2021-01-01 02:14

    Well, this code snippet doesn't tell us much, but there are a couple of obvious errors in your code. First, DOM Event object doesn't have _x and _y properties. but rather clientX and clientY or pageX and pageY. To get relative mouse coordinates from the current event object, you would do something like:

    element.onclick = function(e) {
        var x = e.pageX - this.offsetLeft;
        var y = e.pageY - this.offsetTop;
    }
    

    Next, canvas' 2d context doesn't have a method called circle, but you could write your own, maybe something like:

    var ctx = canvas.context;
    ctx.fillCircle = function(x, y, radius, fillColor) {
        this.fillStyle = fillColor;
        this.beginPath();
        this.moveTo(x, y);
        this.arc(x, y, radius, 0, Math.PI*2, false);
        this.fill();
    }
    

    Anyhow, here's a test html page to test this out: http://jsfiddle.net/ArtBIT/kneDX/

    I hope this helps. Cheers

    0 讨论(0)
提交回复
热议问题