markE..
11
关于Canvas,Canvas'元素',以及`elements'的可见性......
当画布上的任何元素需要更改(移动,擦除等)时,标准方法是完全擦除画布并使用新位置中的元素重绘画布(或者如果元素被删除则不重绘元素).
这是因为画布不"记住"它绘制任何单个元素的位置,因此无法单独移动或擦除任何元素.
在画布被删除后,您需要"记住"有关要重绘的元素的足够信息.
因此,在您的示例中,您可以创建javascript对象a并b表示您的右上角和左下角线路径.
每个对象都有定义其行路径的点和一个标志,指示它是否可见(在画布上可见==重绘).
// 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,
}
为了便于处理,您可以将所有行路径对象放在一个数组中:
// an array containing all the line-path objects
var myObjects=[a,b];
然后,当您清除画布时,只需使用每个对象的线路径信息来重绘该线条.如果特定对象可见性标志是false不重绘该特定对象.
// 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
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
context.lineTo(points[i],points[i+1]);
}
context.stroke();
// restore the context to its untranslated state
context.restore();
}
完成所有这些后,您的按钮只需更改特定线路径对象上的可见性标记,然后清除/重绘整个画布.
// 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);
});