Radu Paise
Radu Paise

Reputation: 285

HTML5 Canvas animation clearRect

I just started HTML5. I have a problem making a line following the mouse. It works if I don't clearRect( if I remove the line context.clearRect(0, 0, canvas.width, canvas.height);). Any ideea? I attached the code. Thanks

<html>
<head>
    <title>Test</title>
</head>
<body>
    <canvas id="myCanvas" width="1000" height="600" style="border:1px solid #c3c3c3;">
        Your browser does not support the canvas element.
    </canvas>
    <script type="text/javascript">

        window.onload = function()
        {

        };

        function captureMousePosition(evt) 
        {
            var c = document.getElementById("myCanvas");
            var context = c.getContext("2d");

            context.clearRect(0, 0, canvas.width, canvas.height);
            context.strokeStyle = 'rgba(0,153,255,0.4)';  
            context.beginPath();
            context.moveTo(0,0);
            context.lineTo(evt.x, evt.y);
            context.stroke();         
        }
        document.captureEvents(Event.MOUSEMOVE);
        document.onmousemove = captureMousePosition;

    </script>
</body>

Upvotes: 0

Views: 5693

Answers (2)

Shamaila Tahir
Shamaila Tahir

Reputation: 998

I have created a jsFiddle for your problem. To me the problem was in evt.x and evt.y, they were undefined. I have pasted my own functions to get mouse coordinates. You can use a simple way but this is the most reliable way.

http://jsfiddle.net/g9xQ2/

Upvotes: 1

Willem Mulder
Willem Mulder

Reputation: 13994

context.clearRect(0, 0, canvas.width, canvas.height);

Will clear the complete canvas, thus erasing the line that was on the canvas so far.

One solution is to clear the canvas only once before you start drawing. For example, clear the canvas at the window.onLoad() event, and then only clear again when you start a new drawing.

A second solution would be to store every mouse movement in a long array and redraw that complete line every frame.

edit: update with regard to your clarification below. The code doesn't work due to a syntax error in the clearRect code. You use 'canvas' which is not defined.

context.clearRect(0, 0, c.width, c.height);

does the trick!

Upvotes: 3

Related Questions