About Canvas, Canvas 'elements', and the visibility of `elements' ...
When any element on the canvas needs to change (move, erase, etc), the standard method is to completely erase the canvas and redraw the canvas with the elements in their new positions (or not redraw the elements if they are erased).
That's because canvas does not "remember" where it drew any individual element and therefore cannot individually move or erase any element.
It's up to you to "remember" enough information about an element to redraw it after the canvas has been erased.
A Demo: http://jsfiddle.net/m1erickson/Wrk2e/
So in your example you could create javascript objects a
and b
to represent your top-right and left-bottom line paths.
Each object would have the points which define its line-path and a flag indicating if it is visible (visible == redrawn on the canvas).
var a={
path:[10 ,10 , 300 ,10 , 300 ,300 ],
isVisible:false ,
}
var b={
path:[10 ,10 , 10 ,300 , 300 ,300 ],
isVisible:false ,
}
Copy
For easy processing you can put all your line-path objects in an array:
var myObjects=[a,b];
Copy
Then when you clear the canvas you simply use each objects line-path information to redraw the line. If a particular objects visibility flag is false
then don't redraw that particular object.
function redrawAll (myObjects ){
context.clearRect (0 ,0 ,canvas.width ,canvas.height );
for (var i=0 ;i<myObjects.length ;i++){
if (myObjects[i].isVisible ){
drawLinePath (myObjects[i]);
}
}
}
function drawLinePath (theObject ){
var points=theObject.path ;
context.save ();
context.translate (0.5 , 0.5 );
context.beginPath ();
context.setLineDash ([2 ,10 ]);
context.moveTo (points[0 ],points[1 ]);
for (var i=2 ;i<points.length ;i+=2 ){
context.lineTo (points[i],points[i+1 ]);
}
context.stroke ();
context.restore ();
}
Copy
With all this in place, your buttons simply change the visibility flag on a particular line-path object and then clear/redraw the entire canvas.
$("#reDrowA" ).on ("click" ,function ( ){
a.isVisible =true ;
redrawAll (myObjects);
});
$("#reDrowB" ).on ("click" ,function ( ){
b.isVisible =true ;
redrawAll (myObjects);
});
$("#clearA" ).on ("click" ,function ( ){
a.isVisible =false ;
redrawAll (myObjects);
});
$("#clearB" ).on ("click" ,function ( ){
b.isVisible =false ;
redrawAll (myObjects);
});
Copy
Post a Comment for "How To Clear Specific Line In Canvas : HTML5"