html如何清除context,如何清除Canvas中的特定行:HTML5

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);

});

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值