JS Class转换为Constructor构造函数失效,饼图无法显示怎么解决
用户提问
我尝试将一段代码从Class类写法改写为Constructor构造函数写法做适配,控制台没有任何报错提示,但实时预览界面中饼图完全没有显示。
我主要是将Slice类和Piechart类替换为了如下代码:
'use strict'; function Slice(lbl, val, strt, fll) { this.label = lbl; this.value = constrain(val, 0.0, 1.0); this.start = constrain(strt, 0.0, TWO_PI); var valAngle = map(this.value, 0.0, 1.0, 0.0, TWO_PI); this.middle = this.start + valAngle * 0.5; this.stop = this.start + valAngle; this.fillFocus = color(fll, 99, 99, 255); this.fillNoFocus = color(fll, 89, 49, 189); this.fill = this.fillNoFocus; this.hasFocus = false; this.labelInset = 0.667; this.toString = function() { return this.label + ": " + (this.value * 100).toFixed(2) + "%"; }; this.draw = function(cx, cy, radius) { if (this.hasFocus) { this.fill = lerpColor(this.fill, this.fillFocus, Slice.focusFadeIn); } else { this.fill = lerpColor(this.fill, this.fillNoFocus, Slice.focusFadeOut); } fill(this.fill); arc(cx, cy, radius, radius, this.start, this.stop); }; this.showLabel = function(cx, cy, radius) { var x = cx + cos(this.middle) * radius * this.labelInset; var y = cy + sin(this.middle) * radius * this.labelInset; fill(0, 0, 0); text(this, x, y); fill(0, 0, 99); text(this, x - 1, y - 1); }; this.hover = function(angle) { angle = angle < 0 ? angle + TWO_PI : angle; return angle > this.start && angle < this.stop; }; }
补充说明:我是编程纯新手,正在练习各类小型教程项目,上述代码写法参考了JavaScript入门课程的教学内容。
修复方案
1. 补充Slice静态属性
原Class写法中Slice定义了两个静态属性focusFadeIn和focusFadeOut,你改写的构造函数版本没有补充这两个属性,导致draw方法中调用lerpColor时传入了undefined值,绘图逻辑直接失效。
在Slice构造函数代码后补充如下代码即可:
Slice.focusFadeIn = 0.08; Slice.focusFadeOut = 0.02;
2. 同步改写Piechart类
你只完成了Slice类的改写,原代码中还有Piechart类的Class定义,如果你运行环境不支持ES6 Class语法,也会导致代码不生效。Piechart类改写为构造函数的参考代码如下:
function Piechart(x, y, rad, lbls, vals) { this.x = x; this.y = y; this.radius = rad; this.slices = []; var sum = vals.reduce(function (a, b) { return a + b; }, 0); var lastAngle = 0.0; var hueOffset = random(0, 360); for (var i = 0; i < vals.length; i++) { var percent = vals[i] / sum; var hue = (i / vals.length * 360 + hueOffset) % 360; this.slices.push(new Slice(lbls[i], percent, lastAngle, hue)); lastAngle += map(percent, 0.0, 1.0, 0.0, TWO_PI); lastAngle %= TWO_PI; } this.draw = function() { push(); translate(this.x, this.y); for (var i = 0; i < this.slices.length; i++) { this.slices[i].draw(0, 0, this.radius); } for (var i = 0; i < this.slices.length; i++) { this.slices[i].showLabel(0, 0, this.radius); } pop(); var a = atan2(mouseY - this.y, mouseX - this.x); for (var i = 0; i < this.slices.length; i++) { this.slices[i].hasFocus = dist(mouseX, mouseY, this.x, this.y) < this.radius * 0.5 && this.slices[i].hover(a); } }; }
3. 检查基础依赖和入口逻辑
确认p5.js库已正确加载,你代码中用到的constrain、map、color、lerpColor都是p5.js的内置方法,缺失依赖也会导致绘图失败。同时检查setup、draw入口函数中是否正确初始化了Piechart实例并调用了其draw方法。
内容的提问来源于stack exchange,提问作者soyNstacks
相关产品推荐
相关产品推荐

