2012-11-17 5 views
11

Ich verwende dieses javaScript auf dem Körper onmousemove Funktion:clearRect Funktion löscht nicht die Leinwand

function lineDraw() { 
    //Get the context and the canvas: 
    var canvas=document.getElementById("myCanvas"); 
    var context=canvas.getContext("2d"); 
    //Clear the last canvas 
    context.clearRect(0, 0, canvas.width,canvas.height); 
    //Draw the line: 
    context.moveTo(0,0); 
    context.lineTo(event.clientX,event.clientY); 
    context.stroke(); 

} 

Es soll die Leinwand jedes Mal, wenn ich die Maus bewegen, löschen und eine neue Linie zeichnen, aber es funktioniert nicht richtig. Ich versuche es zu lösen, ohne jQuery, Maushörer oder ähnliches zu verwenden. Hier

ist der Code:

http://jsfiddle.net/7vx2z/

Antwort

22

sollten Sie verwenden "beginPath()". Das ist es.

function lineDraw() { 
    var canvas=document.getElementById("myCanvas"); 
    var context=canvas.getContext("2d"); 
    context.clearRect(0, 0, context.width,context.height); 
    context.beginPath();//ADD THIS LINE!<<<<<<<<<<<<< 
    context.moveTo(0,0); 
    context.lineTo(event.clientX,event.clientY); 
    context.stroke(); 
} 
+0

Diese Antwort wurde als für die Korrektheit akzeptiert markiert. –

+0

Ich möchte hinzufügen, dass dies auch für Draw-Methoden wie Rect und Arc gilt. – MetalGodwin

+1

Es ist alt aber ... 'closePath' ist nutzlos und irreführend hier, es ist nur ein' lineTo (previousStartingPointOfThePath) 'also für eine einzelne Zeile, es wird nichts tun, und es sagt überhaupt nicht, dass Sie Ihre beendet haben Pfadangabe – Kaiido

-1

Versuchen mit context.canvas.width = context.canvas.width:

function lineDraw() { 
    var canvas=document.getElementById("myCanvas"); 
    var context=canvas.getContext("2d"); 
    //context.clearRect(0, 0, context.width,context.height); 
    context.canvas.width = context.canvas.width; 
    context.moveTo(0,0); 
    context.lineTo(event.clientX,event.clientY); 
    context.stroke(); 
} 

Demo HERE

+0

oder einfach 'myCanvas.width = myCanvas.width;'. –