打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
HTML5 Canvas绘制圆点虚线实例

HTML5 Canvas 提供了很多图形绘制的函数,但是很可惜,Canvas API只提供了画实线的函数(lineTo),却并未提供画虚线的方法。这样的设计有时会带来很大的不便,《JavaScript权威指南》的作者David Flanagan就认为这样的决定是有问题的,尤其是在标准的修改和实现都比较简单的情况下 (“…something that is so trivial to add to the specification and so trivial to implement… I really think you’re making a mistake here” — http://lists.whatwg.org/pipermail/whatwg-whatwg.org/2007-May/011224.html)。

在Stack Overflow上,Phrogz提供了一个自己的画虚线的实现(http://stackoverflow.com/questions/4576724/dotted-stroke-in-canvas),严格的说,这是一个点划线的实现(p.s. 我认为该页面上Rod MacDougall的简化版更好)。那么,如果需要画圆点虚线(如下图所示),应该怎么办呢?



以下是我自己的实现,只支持画水平的和垂直的圆点虚线,可以参考Phrogz与Rod MacDougall的方法来添加斜线描画的功能。


复制代码
代码如下:

var canvasPrototype = window.CanvasRenderingContext2D && CanvasRenderingContext2D.prototype;
canvasPrototype.dottedLine = function(x1, y1, x2, y2, interval) {
if (!interval) {
interval = 5;
}
var isHorizontal=true;
if (x1==x2){
isHorizontal=false;
}
var len = isHorizontal ? x2-x1 : y2-y1;
this.moveTo(x1, y1);
var progress=0;
while (len > progress) {
progress += interval;
if (progress > len) {
progress = len;
}
if (isHorizontal) {
this.moveTo(x1+progress,y1);
this.arc(x1+progress,y1,1,0,2*Math.PI,true);
this.fill();
} else {
this.moveTo(x1,y1+progress);
this.arc(x1,y1+progress,1,0,2*Math.PI,true);
this.fill();
}
}
}

本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
开发者值得关注的HTML5新特性Canvas
HTML5应用——简易播放器
HTML5基础,第4部分:点睛之笔Canvas
第一阶段复习~HTML5基础夯实
网页|HTML5 也可以画一画(canvas)
Canvas画笔的基本使用
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服