首页 > 作文

基于 HTML5 Canvas 的拓扑组件开发

更新时间:2023-04-03 01:27:47 阅读: 评论:0

在现在前端圈大行其道的 react 和 vue 中,可复用的组件可能是他们大受欢迎的原因之一,

在 ht 的产品中也有组件的概念,不过在 ht 中组件的开发是依托于 html5 canvas 的技术去实现的,

也就是说如果你有过使用 canvas 的开发经验你就可以来封装自己的组件。

下面我以一个进度环为例,来探究一下如何使用ht.js封装出一个拓扑组件。

效果图

代码实现

前置知识

除了ht预定义的组件类型外,用户还可以自定义扩展类型,自定义有两种方式:

直接将type值设置成绘制函数:function(g, rect, comp, data, view){}通过ht.default.tcomptype(name, funtion(g, rect, comp, data, view){})注册组件类型,矢量type值设置成相应的注册名

在这里我选用第一种通过形如

ht.default.timage(
‘circle-progress-bar’, {
width:
100,
height:
100,
comps: [ {
type:
function(g, rect, comp, data, view) {
// … } } ] });

这样的方式完成组件的声明,那么 function(g, rect, comp, data, view) { }中的内容就是我们接下来需要关注的了

准备工作

抽象并声明出几个 coding 中需要的变量

进度百分比 progresspercentage {百分比}圆环渐变色 linearouter {颜色数组}内圆渐变色 linearinner {颜色数组}字体缩放比例 fontscale {数字}显示原始值 showorigin {布尔}进度条样式 progresslinecap {线帽样式}

变量的声明和赋值了

var x = rect.x;var y = rect.y;var rectwidth = rect.width;vlol s7总决赛a教育学专业r rectheight = rect.height;var width = rectwidth < rectheight ? rectwidth : rectheight;var progresspercentage = parfloat((data.a('progresspercentage') * 100).tofixed(10));var fontscale = data.a('fontscale');var showorigin = data.a('showorigin');var backgroundcolor = data.a('backgroundcolor');var progresslinecap = data.a('progresslinecap');var fontsize = 16; // 字体大小var posx = x + rectwidth / 2; // 圆心 x 坐标var posy = y + rectheight / 2; // 圆心 y 坐标var circlelinewidth = width / 10; // 圆环线宽var circleradius = (width - circlelinewidth) / 2; // 圆环半径var circleangle = {sangle: 0, eangle: 2 * math.pi}; // 绘制背景圆和圆环内圆所需的角度var prostartangel = math.pi; // 进度环起始角度var proendangel = prostartangel + ((math.pi * 2) / 100) * progresspercentage; // 进度环结束角度

创建渐变色样式

var grd = context.createlineargradient(x1, y1, x2, y2);grd.addcolorstop(0, 'red');   grd.addcolorstop(1, 'blue');

在 canvas 中的渐变色是按照如上方式来创建的,但是在一个组件中去如果一个一个去添加显然是去组件的理念是背道而驰的,所以我选择封装一个函数根据颜色数组中的各个颜色来生成渐变色样式

// 创建渐变色样式函数function addcreatelinear(colorsarr) {    var linear = rectwidth < rectheight        ? g.createlineargradient(x, posy - width / 2, width, posy + width / 2)        : g.createlineargradient(posx - width / 2, y, posx + width / 2, width);    var len = colorsarr.length;    for (var key in colorsarr) {        linear.addcolorstop((+key + 1) / len, colorsarr[key]);    }    return linear;}// 创建渐变填充颜色var linearouter = addcreatelinear(data.a('linearouter'));var linearinner = addcreatelinear(data.a('linearinner'));

开始 coding

准备工作结束后下面就是 canvas 的时间了

绘制背景圆

g.beginpath();g.arc(posx, posy, circleradius, circleangle.sangle, circleangle.eangle);g.clopath();g.fillstyle = backgroundcolor;g.fill();g.linewidth = circlelinewidth;g.strokestyle = backgroundcolor;g.stroke();

绘制进度环

g.beginpath();g.arc(posx, posy, circleradius, prostartangel, proendangel);g.strokestyle = linearouter;g.linewidth = circlelinewidth;g.linecap = progresslinecap;if (progresspercentage !== 0) g.stroke();

绘制中心圆

g.beginpath();g.fillstyle = linearinner;g.arc(posx, posy, circleradius - circlelinewidth / 2 - 1, 0, math.pi * 2, fal);g.strokestyle = '#0a2e44';g.fill();g.linewidth = 2;g.stroke();

绘制文字

g.fillstyle = 'white';g.textalign = 'center';g.font = fontsize + 'px arial';g.translate(posx * (1 - fontscale), posy * (1 - fontscale));g.scale(fontscale, fontscale);showorigin    ? g.filltext(progresspercentage / 100, posx, posy + fontsize / 3)    : g.filltext(progresspercentage + '%', posx, posy + fontsize / 3);

最后通过简单的配置就可以在网页上呈现出这个进度环了

var datamodel = new ht.datamodel();var graphview = new ht.graph.graphview(datamodel);var circle1 = new ht.node();circle1.tposition(150, 150);circle1.tsize(200, 200);circle1.timage('circle-progress-bar');circle1.a({    progresspercentage: 0.48,    linearouter: ['#26a67b', '#0474d6'],    linearinner: ['#004e92', '#000000'],    fontscale: 1,    showorigin: true,    progresslinecap: 'butt',    backgroundcolor: 'rgb(61,61,61)'});datamodel.add(circle1);// 这次多生成几个 不过代码相似 在此就不赘述了

完整代码如下

ht.default.timage('circle-progress-bar', {    width: 100,    height: 100,    comps: [        {            type: function(g, rect, comp, data, view) {                // 获取属性值                var x = rect.x;                var y = rect.y;                var rectwidth = rect.width;                var rectheight = rect.height;                var width = rectwidth < rectheight ? rectwidth : rectheight;                var progresspercentage = parfloat((data.a('progresspercentage') * 100).tofixed(10));                var fontscale = data.a('fontscale');                var showorigin = data.a('showorigin');                var backgroundcolor = data.a('backgroundcolor');                var progresslinecap = data.a('progresslinecap');                var fontsize = 16;                // 定义属性值                var posx = x + rectwidth / 2;                var posy = y + rectheight / 2;                var circlelinewidth = width / 10;                var circleradius = (width - circlelinewidth) / 2;                var circleangle = {                    sangle: 0,                    eangle: 2 * math.pi                };                var prostartangel = math.pi;                var proendangel = prostartangel + ((math.pi * 2) / 100) * progresspercentage;                // 创建渐变背景色                function addcreatelinear(colorsarr) {                    var linear = rectwidth < rectheight ? g.createlineargradient(x, posy - width / 2, width, posy + width / 2) : g.createlineargradient(posx - width / 2, y, posx + width / 2, width);                    var len = colorsarr.length;                    colorsarr.foreach(function(item, index) {                        linear.addcolors操姨top((index + 1) / len, item);                    });                    return linear;                }                // 创建渐变填充颜色                var linearouter = addcreatelinear(data.a('linearouter'));                var linearinner = addcreatelinear(data.a('linearinner'));                // 0.保存绘制前状态                g.save();                // 1.背景圆                g.beginpath();                g.arc(posx, posy, circleradius, circleangle.sangle, circleangle.eangle);                g.clopath();                g.fillstyle = backgroundcolor;                g.fill();                g.linewidth = circlelinewidth;                g.strokestyle = backgroundcolor;                g.stroke();                // 2.进度环                g.beginpath();                g.arc(posx, posy, circleradius, prostartangel, proendangel);                g.strokestyle = linearouter;                g.linewidth = circlelinewidth;                g.linecap = progresslinecap;                if (progresspercentage !== 0) g.stroke();                // 3.绘制中心圆                g.beginpath();                g.fillstyle = linearinner;                g.arc(posx, posy, circleradius - circlelinewidth / 2 - 1, 0, math.pi * 2, fal);                g.strokestyle = '#0a2e44';                g.fill();                g.linewidth = 2;                g.stroke();                // 4.绘制文字                g.fillstyle = 'white';                g.textalign = 'center';                g.font = fontsize + 'px arial';                g.translate(posx * (1 - fontscale), posy * (1 - fontscale));                g.scale(fontscale, fontscale);                showorigin ? g.filltext(progresspercentage / 100, posx, posy + fontsize / 3) : g.filltext(progresspercentage + '%', posx, posy + fontsize / 3);                // 5.恢复绘制前状态                g.restore();            }        }    ]});

view code

几点心得

声明属性

在这个部分有几点可供参考

使用小驼峰对属性进行命名,并且少用缩写尽量语义化

举个栗子:

fontscale 字体缩放比例progresspercentage 进度百分比

属性值类型的选择也要尽量贴合属性的含义

举个栗子:

一个存储着几个颜色值字符串的数组,用颜色数组就比单纯的数组更为贴切一个表示画珍爱生命的句子笔线帽种类的字符串,用线帽样式就比字符转更为贴切

使用属性

由于进度环是一个圆形的组件,那么在这里有两点供参考

当组件的 rect.widthrect.height 不相等的时候我们需要自己来设定一个 width,

让圆在这个以 width 为边的正方形中绘制,而 width 的值就是 rect.widthrect.height 中较短的一边,

而这么做的理由是这样绘制圆自适应性能力会更好,并且圆心也直会在 (rect.width/2, rect.height/2)这一点上。

var rectwidth = rect.width;var rectheight = rect.height;var width = rectwidth < rectheight ? rectwidth : rectheight;

由于我们自己设定了一个 width,那么在设置渐变颜色的参数上就需要注意一下了。

当 rect.width 不等于 rect.height 的时候。

如果按照 g.createlineargradient(0, 0, rect.width, rect.height) 设置渐变色就会出现下面的效果,右下方的蓝色不见了。

不过如果按照如下代码的方式设置渐变色就会出现下面的效果就会出现预期的效果了。

  var posx = rectwidth / 2;  var posy = rectheight / 2;  var linear = rectwidth < rectheight          ? g.createlineargradient(0, posy - width / 2, width, posy + width / 2)          : g.createlineargradient(posx - width / 2, 0, posx + width / 2, width);

原因其实很简单,就是渐变颜色方向的起点和终点并没有随着 width 的改变而改变。

如图所示以rectwidth > rectheight 为例

绘制组件

在绘制组件的过程中,我们需要把一些边界条件和特殊情况考虑到,来保持组件的扩展性和稳定性

下面就是一些我的心得

在做了 g 操作的头尾分别使用 saverestore ,以此来保障 g 操作的不影响后续的扩展开发。

g.save()// g 操作// ...// ...g.restore()

设想一下,我们正在用 10 像素宽,颜色为红色的笔画图,然后把画笔设置成1像素宽,颜色变成绿色。绿色画完之后呢,我们想接着用10像素的红色来画,如果没有 save 与 restore,那我们就不得不重新设置一遍画笔——如果画笔状态过多,那我们的代码就会大量增加;而且,这些设置过程是重复而乏味的。

最后保存的最先还原!restore 总是还原离他最近的 save 点(已经还原的不能第2次还原到他)。

另外save和restore一般是改变了transform或clip才需要,大部分情况下不需要,例如你设置了颜色、宽度等等参数,下次要绘制这些的人会自己再设置这些,所以能尽量不用save/restore的地方可以尽量不用,那也是有代价的

当进度值为 0 且 线帽样式为圆角的时候进度环会变成一个圆点,正确的做法使需要对进度值为 0 的时候进行特殊处理。

// 进度环g.beginpath();g.arc(posx, posy, circleradius, prostartangel, proendangel);g.strokestyle = linearouter;g.linecap = progresslinecap;if (progresspercentage !== 0) g.stroke();

由于 chr保护大自然的作文ome 浏览器的限制(chrome 显示最小字体为 12 px),所以不能通过 12px这样的数值设定文字大小,只能通过缩放来控制文字的大小了。

当你高高兴兴的的使用 scale 对文字进行缩放的时候

var fontscale = 0.75g.fillstyle = 'white';g.textalign = 'center';g.font = fontsize + 'px arial';g.scale(fontscale, fontscale);g.filltext(progresspercentage + '%', posx, posy + fontsize / 3);

你会得到这样的结果

造成这个结果的原因是 scale 操作的参考点位置不对

下面我们使用矩形的例子详细解释一下

  // 原矩形  ctx.save();  ctx.beginpath();  ctx.strokerect(0, 0, 400, 400);  ctx.restore();  // 缩放后的矩形  ctx.save();  ctx.beginpath();  ctx.scale(0.75, 0.75);  ctx.strokerect(0, 0, 400, 400);  ctx.restore();

这时 scale 的参考点是(0,0)所以,中心缩放没有按照我们预期的进行

当修改参考点的坐标为(50,50)之后,中心缩放就正常了

那么这个(50,50)是怎么得来的?

根据上图我们不难看出这个距离其实就是 (缩放前的边长 - 缩放后的边长) / 2得到得

公式就是 width * (1 - scale) / 2

在这个例子中套用一下就是 400 * (1 - 0.75) / 2 = 50

  // 原矩形  ctx.save();  ctx.beginpath();  ctx.strokerect(0, 0, 400, 400);  ctx.restore();  // 缩放后的矩形  ctx.save();  ctx.beginpath();  ctx.translate(50, 50)  ctx.scale(0.75, 0.75);  ctx.strokerect(0, 0, 400, 400);  ctx.restore();

我们把上面得公式在做进一步的扩展,让它的适用性更强

  width * (1 - scale) / 2   -> width / 2 * (1 - scale)  -> posx * (1 - scale)  height * (1 - scale) / 2  -> height / 2 * (1 - scale) -> posy * (1 - scale)

在这里也需要明确一点 posx = x + (width / 2) posy = y + (height / 2)

在进一步抽象成函数

  function centerscale(ctx, posx, posy, scalex, scaley) {      ctx.translate(posx * (1 - scalex), posy * (1 - scaley));      ctx.scale(scalex, scaley);  }

那么其中的文字缩放也是如出一辙

  var fontscale = 0.75  g.fillstyle = 'white';  g.textalign = 'center';  g.font = fontsize + 'px arial';  g.translate(posx * (1 - fontscale), posy * (1 - fontscale));  g.scale(fontscale, fontscale);  g.filltext(progresspercentage + '%', posx, posy + fontsize / 3);

当然结果也是很不错的

本文发布于:2023-04-03 01:27:45,感谢您对本站的认可!

本文链接:https://www.wtabcd.cn/fanwen/zuowen/7db06f4c15e6b2160a81df6872700669.html

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。

本文word下载地址:基于 HTML5 Canvas 的拓扑组件开发.doc

本文 PDF 下载地址:基于 HTML5 Canvas 的拓扑组件开发.pdf

标签:组件   缩放   进度   颜色
相关文章
留言与评论(共有 0 条评论)
   
验证码:
Copyright ©2019-2022 Comsenz Inc.Powered by © 专利检索| 网站地图