Search code examples
mouseeventraphaelmousedownmouseup

RaphaelJS: mouseup and mousedown calling the same function?


I'm learning Raphael and I wonder how to call the same function from both events, mousedown and mouse up, in order to draw two dots with every click.

You can test the code here: jsfiddle

var w = window.innerWidth;
var h = window.innerHeight;

var paper = Raphael(0, 0, w, h);

var canvas = paper.rect(0, 0, w, h,12);
canvas.attr('fill', 'lightgrey');

canvas.mouseup(function (event, a, b) {
    // get bounding rect of the paper
    var bnds = event.target.getBoundingClientRect();
    var targetBox = this.getBBox();

    // adjust mouse x/y
    var mx = event.clientX - bnds.left;
    var my = event.clientY - bnds.top;

    // divide x/y by the bounding w/h to get location %s and apply factor by actual paper w/h
    var fx = mx/bnds.width * canvas.attrs.width + targetBox.x;
    var fy = my/bnds.height * canvas.attrs.height + targetBox.y;

    // cleanup output
    fx = Number(fx).toPrecision(3);
    fy = Number(fy).toPrecision(3);

    paper.circle(fx, fy, 1).attr("fill","black", "stroke-width",0);
});

I'm pretty new to RaphaelJS, and I did never need to call a function from two mouse events with javascript. So, I'm confused. Any help will be appreciated.


Solution

  • You can just create a new function, which takes in the event parameter, like this...

    canvas.mouseup( eventDraw );
    canvas.mousedown( eventDraw );
    
    function eventDraw( event ) {
        //... do stuff
    };
    

    jsfiddle