接上一篇,在用canvas实现验证码的时候原先的代码是:
context.fillRect(0, 0, canvas.width, canvas.height);
context.clearRect(0, 0, canvas.width, canvas.height);
思路是先填充目标区域,再清空填充色获得无边框白色画布。
但左右一想这方法实在太蠢,于是改了一下:
context.strokeStyle = "#FFF";
context.strokeRect(0, 0, canvas.width, canvas.height);
即绘制无填充的矩形,再将其笔触设为白色实现无边框。
但在每次点击canvas更换验证码时会出现叠加的现象:
稍微思考便可得知是由于每次给画布填充完内容没有清空,导致一次次叠加;
所以改进了代码:
context.clearRect(0,0,canvas.width,canvas.height);
context.strokeStyle = "#FFF";
context.strokeRect(0, 0, canvas.width, canvas.height);
进一步研究代码,既然每次都需要先清空画布再画无边框的白色背景矩形,那是不是第一步的清空矩形相当于是做了生成白底无边框矩形的任务呢??
于是试了一试:
context.clearRect(0,0,canvas.width,canvas.height);
果然如设想一般能不出现bug的同时实现需求!
所以可以得出结论clearRect()语句也可以用来绘制空白画布,与strokeRect()并无区别。