绘制垂直线时clearRect不会清除画布 [英] clearRect does not clear the canvas when drawing vertical lines

查看:34
本文介绍了绘制垂直线时clearRect不会清除画布的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在工作时遇到了一个奇怪的边缘案例,用画布构建了一些东西.在绘制从画布顶部到底部的垂直线时,clearRect 不会清除画布.渲染其他东西时,clearRect 工作正常.

I hit a weird edge case building something with canvas at work. clearRect does not clear the canvas when drawing vertical lines that go from the top to the bottom of the canvas. When rendering other stuff, clearRect works fine.

我不确定我是否遗漏了一些明显的东西,这是有意的行为,还是浏览器错误(不太可能,因为 mac 上的 chrome、safari、firefox 和 opera 中的行为是相同的).如果是故意行为,是否有人知道其背后的基本原理和/或可以指向一些文档?

I'm not sure if I am missing something obvious, if this is intentional behavior, or a browser bug (unlikely since the behavior is identical in chrome, safari, firefox and opera on mac). If it is intentional behavior, does anybody know the rationale behind it and/or can perhaps point to some documentation?

我做了一个小测试用例,清楚地显示了行为,只有组合 clearRect/vertical 线不会清除画布:http://jsfiddle.net/kZj6F/

I made a small test case that shows the behavior clearly, only the combination clearRect/vertical lines does not clear the canvas: http://jsfiddle.net/kZj6F/

谢谢!

推荐答案

您的问题是缺少 beginPath 导致后续行添加到与 stroke 绘制所有线条.

Your issue is with a missing beginPath causing subsequent lines to be added to the same path that was stroke drawing all lines.

如果您使用 clearRect 选项切换到点并返回到线,您还可以看到最后一个 arc 添加到正在绘制的路径中.只需添加一个调用 ctx.beginPath(); before ctx.moveTo(randomX + 0.5, 0);ctx.lineTo(randomX + 0.5, canvas.height); 问题解决了.

If you switch to dots and back to lines with the clearRect option choose you can see the last arc added to the path being drawn too. Just add a call ctx.beginPath(); prior ctx.moveTo(randomX + 0.5, 0); ctx.lineTo(randomX + 0.5, canvas.height); and the problem is solved.

您可以检查 http://jsfiddle.net/kZj6F/1/ 以查看它是否正常工作.

You can check http://jsfiddle.net/kZj6F/1/ to see it working.

如果其他形状被添加到路径中并且路径没有被清除,那么它也会与其他形状一起使用.

Bwt it will with other shapes too if they got added to the path and the path was not cleared.

这篇关于绘制垂直线时clearRect不会清除画布的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆