资讯

精准传达 • 有效沟通

从品牌网站建设到网络营销策划,从策略到执行的一站式服务

HTML5中如何利用Canvas自定义圆角矩形

这篇文章主要讲解了“HTML5中如何利用Canvas自定义圆角矩形”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“HTML5中如何利用Canvas自定义圆角矩形”吧!

创新互联专业提供成都主机托管四川主机托管成都服务器托管四川服务器托管,支持按月付款!我们的承诺:贵族品质、平民价格,机房位于中国电信/网通/移动机房,雅安服务器托管服务有保障!

HTML5 Canvas自定义圆角矩形与虚线(RoundedRectangle and Dash Line)
实现向HTML Canvas 2d context绘制对象中添加自定义的函数功能演示,如何绘制虚线以及控制虚线间隔大小,学会绘制圆角矩形的技巧。
HTML5 Canvas绘制对象中提供的原生功能没有实现绘制圆角矩形与虚线的功能,但是通过JavaScript语言的Object.prototype可以实现对对象CanvasRenderingContext2D添加这两个函数功能。代码的演示效果如下:
HTML5中如何利用Canvas自定义圆角矩形 
组件fishcomponent.js的代码如下:

代码如下:

CanvasRenderingContext2D.prototype.roundRect =
function(x, y, width, height, radius, fill, stroke) {
if (typeof stroke == "undefined") {
stroke = true;
}
if (typeof radius === "undefined") {
radius = 5;
}
this.beginPath();
this.moveTo(x + radius, y);
this.lineTo(x + width - radius, y);
this.quadraticCurveTo(x + width, y, x + width, y + radius);
this.lineTo(x + width, y + height - radius);
this.quadraticCurveTo(x + width, y + height, x + width - radius, y+ height);
this.lineTo(x + radius, y + height);
this.quadraticCurveTo(x, y + height, x, y + height - radius);
this.lineTo(x, y + radius);
this.quadraticCurveTo(x, y, x + radius, y);
this.closePath();
if (stroke) {
this.stroke();
}
if (fill) {
this.fill();
}
};
CanvasRenderingContext2D.prototype.dashedLineTo = function (fromX, fromY, toX, toY, pattern) {
// default interval distance -> 5px
if (typeof pattern === "undefined") {
pattern = 5;
}
// calculate the delta x and delta y
var dx = (toX - fromX);
var dy = (toY - fromY);
var distance = Math.floor(Math.sqrt(dx*dx + dy*dy));
var dashlineInteveral = (pattern <= 0) ? distance : (distance/pattern);
var deltay = (dy/distance) * pattern;
var deltax = (dx/distance) * pattern;
// draw dash line
this.beginPath();
for(var dl=0; dlif(dl%2) {
this.lineTo(fromX + dl*deltax, fromY + dl*deltay);
} else {
this.moveTo(fromX + dl*deltax, fromY + dl*deltay);
}
}
this.stroke();
};


HTML中调用演示:

代码如下:







Canvas Rounded Rectangle Demo





HTML5 Canvas Dash-line Demo - By Gloomy Fish


Dash line and Rounded Rectangle





感谢各位的阅读,以上就是“HTML5中如何利用Canvas自定义圆角矩形”的内容了,经过本文的学习后,相信大家对HTML5中如何利用Canvas自定义圆角矩形这一问题有了更深刻的体会,具体使用情况还需要大家实践验证。这里是创新互联,小编将为大家推送更多相关知识点的文章,欢迎关注!


标题名称:HTML5中如何利用Canvas自定义圆角矩形
链接地址:http://cdkjz.cn/article/jpsgih.html
多年建站经验

多一份参考,总有益处

联系快上网,免费获得专属《策划方案》及报价

咨询相关问题或预约面谈,可以通过以下方式与我们联系

业务热线:400-028-6601 / 大客户专线   成都:13518219792   座机:028-86922220