Skip to content Skip to sidebar Skip to footer

Draw A Line With Two Mouse Clicks On Html5 Canvas?

How do I draw a line with two mouse clicks on canvas?

Solution 1:

The code is quite simple, but you have to get a good foundation:

Demo: http://jsfiddle.net/NpDdt/10/

JavaScript:

var clicks = 0;
var lastClick = [0, 0];

document.getElementById('canvas').addEventListener('click', drawLine, false);

functiongetCursorPosition(e) {
    var x;
    var y;

    if (e.pageX != undefined && e.pageY != undefined) {
        x = e.pageX;
        y = e.pageY;
    } else {
        x = e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;
        y = e.clientY + document.body.scrollTop + document.documentElement.scrollTop;
    }

    return [x, y];
}

functiondrawLine(e) {
    context = this.getContext('2d');

    x = getCursorPosition(e)[0] - this.offsetLeft;
    y = getCursorPosition(e)[1] - this.offsetTop;

    if (clicks != 1) {
        clicks++;
    } else {
        context.beginPath();
        context.moveTo(lastClick[0], lastClick[1]);
        context.lineTo(x, y, 6);

        context.strokeStyle = '#000000';
        context.stroke();

        clicks = 0;
    }

    lastClick = [x, y];
};

Solution 2:

Here is a complete example, based on the W3Schools example at http://www.w3schools.com/html5/tryit.asp?filename=tryhtml5_canvas_line

<!DOCTYPE html><html><head><title></title><metahttp-equiv="Content-Type"content="text/html; charset=UTF-8"><scriptsrc="http://code.jquery.com/jquery-1.6.1.min.js"></script><script>

            $(function(){

                var point1 = newArray();
                point1['x'] = false;
                point1['y'] = false;
                var point2 = newArray();
                point2['x'] = false;
                point2['y'] = false;

                var c=document.getElementById("myCanvas");
                var cxt=c.getContext("2d");

                $(document).click(function(e){
                    if ( false === point1['x'] || false === point1['y']) {
                        point1['x'] = e.pageX;
                        point1['y'] = e.pageY;
                        return;
                    }
                    elseif ( false === point2['x'] || false === point2['y'] ) {
                        point2['x'] = e.pageX;
                        point2['y'] = e.pageY;

                        console.log("second");

                        cxt.moveTo(point1['x'], point1['y']);
                        cxt.lineTo(point2['x'], point2['y']);
                        cxt.stroke();

                    }


                });
            });
        </script></head><body><canvasid="myCanvas"width="200"height="200"style="border: 1px solid #000">Your browser does not support the canvas element.</canvas></body></html>

Post a Comment for "Draw A Line With Two Mouse Clicks On Html5 Canvas?"