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).
// create an object containing the top-right lines
// the object contains its path points & if it is visible or not
var a={
path:[10,10, 300,10, 300,300],
isVisible:false,
}
// create an object containing the left-bottom lines
// the object contains its path points & if it is visible or not
var b={
path:[10,10, 10,300, 300,300],
isVisible:false,
}
For easy processing you can put all your line-path objects in an array:
// an array containing all the line-path objects
var myObjects=[a,b];
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.
// clear the entire canvas
// redraw any line-paths that are visible
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]);
}
}
}
// redraw 1 line-path
function drawLinePath(theObject){
var points=theObject.path;
// save the current untranslated context state
context.save();
// draw lines through each point in the objects path
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();
// restore the context to its untranslated state
context.restore();
}
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.
// use buttons to set & clear the visibility flags on objects
// In all cases, clear the entire canvas and redraw any visible objects
$("#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);
});