locked
How to draw a line by mouse in canvas RRS feed

  • Question

  • Hi all,

    How to draw a line by mouse in canvas? I mean, using mouse single click canvas, and at this time, the start point is defined. And move your mouse, a new line is drawn which from start point to the current mouse point. If you continue movint your mouse, and old line is erased, and another new line is created. It still from start point to the current mouse point.

    currently, I cannot erase the old line when moving my mouse. The below is my test code. thanks.

        function CanvasSingleMouseMove(e) {
            if (DrawState == 3 && LineStartX != -1 && LineStartY != -1) {
                var objCanvas = $("#myCanvas");
                if (objCanvas.length > 0) {
                    var CanvasTop = $("#myCanvas").offset().top;
                    var CanvasLeft = $("#myCanvas").offset().left;
                    var objContext = objCanvas[0].getContext("2d");
    //                if (LineEndX != null && LineEndY != null) {
    //                    $("#log").html(LineStartX + "," + LineStartY + "," + LineEndX + "," + LineEndY);
    //                    objContext.clearRect(LineStartX, LineStartY, LineEndX, LineEndY);
    //                    objContext.clearRect(LineStartY, LineStartX, LineEndY, LineEndX);
    //                    objContext.clearRect(LineEndX, LineEndY, LineStartX, LineStartY);
    //                }
                    LineEndX = e.pageX - CanvasLeft;
                    LineEndY = e.pageY - CanvasTop;
                    
                    objContext.beginPath();
                    objContext.moveTo(LineStartX, LineStartY);
                    objContext.lineTo(LineEndX, LineEndY);
                    objContext.stroke();
                }
            }
        }

    Wednesday, May 8, 2013 8:49 AM

Answers

  • I have resolved it by myself.

    by using getImageData() and putImageData()

    • Marked as answer by JoeyWang Thursday, May 9, 2013 8:44 AM
    Thursday, May 9, 2013 8:44 AM

All replies

  • Can i use save() and restore() to do it? I tried it, but never successfully.
    Wednesday, May 8, 2013 8:51 AM
  • there is example like http://devfiles.myopera.com/articles/649/example5.html

    this example is implemented by clear all canvas to erase the old line. But what I want is just remove the only line not whole canvas, since the canvas also has some other objects.

    Thursday, May 9, 2013 7:45 AM
  • I have resolved it by myself.

    by using getImageData() and putImageData()

    • Marked as answer by JoeyWang Thursday, May 9, 2013 8:44 AM
    Thursday, May 9, 2013 8:44 AM