我正在尝试创建一个可以帮助我显示圆形进度条的功能。但是我有一个问题: 未捕获的TypeError:ctx.clearRect不是函数
function generateSubject(subjectNumber ,name, firstAttestation, secondAttestation, rating, semester) {
let ratingBar = document.getElementById('rating-bar');
let canvasBar = document.createElement('canvas');
canvasBar.className = 'round-progress-bars ' + subjectNumber;
canvasBar.style.width = '70px';
canvasBar.style.height = '70px';
ratingBar.appendChild(canvasBar);
return canvasBar
}
let bars = [];
bars.push(generateSubject(1));
let rating1 = [80];
roundAnimation(bars, rating1);
function roundAnimation(bars, rating) {
for (let i = 0; i < bars.length; i++) {
let sim;
let ctx = bars[i];
let al = [];
for (let j = 0; j < bars.length; j++) {
al.push(0);
}
let start = 4.72;
let cw = 70;
let ch = 70;
let diff;
function progressSim(){
console.log(i);
diff = ((al[i] / 100) * Math.PI*2*10).toFixed(2);
ctx.clearRect(0, 0, cw, ch);
ctx.lineWidth = 10;
ctx.fillStyle = '#2F80ED';
ctx.strokeStyle = "#2F80ED";
ctx.textAlign = 'center';
ctx.font = '18px Roboto';
ctx.fillText(al[i], cw*.5, ch*.5+5, cw);
ctx.beginPath();
ctx.arc(35, 35, 30, start, diff/10+start, false);
ctx.stroke();
if(al[i] >= rating[i]){
clearTimeout(sim);
// Add scripting here that will run when progress completes
}
else {
al[i]++;
}
}
sim = setInterval(progressSim, 40);
}
}
<div id="rating-bar"></div>
我上面描述的第一个函数生成了元素canvas。
第二个功能为圆形进度条绘制动画。
里面有一个错误: index.js:86未捕获的TypeError:ctx.clearRect不是函数 在progressSim
我该如何解决这个问题?
答案 0 :(得分:1)
您试图直接在context
而不是画布的上下文上调用canvas
方法。您需要先使用.getContext("2d")
的{{1}}方法,然后在该调用返回的上下文中调用这些方法。
canvas
function generateSubject(subjectNumber ,name, firstAttestation, secondAttestation, rating, semester) {
let ratingBar = document.getElementById('rating-bar');
let canvasBar = document.createElement('canvas');
canvasBar.className = 'round-progress-bars ' + subjectNumber;
canvasBar.style.width = '70px';
canvasBar.style.height = '70px';
ratingBar.appendChild(canvasBar);
return canvasBar
}
let bars = [];
bars.push(generateSubject(1));
let rating1 = [80];
roundAnimation(bars, rating1);
function roundAnimation(bars, rating) {
for (let i = 0; i < bars.length; i++) {
let sim;
let ctx = bars[i].getContext("2d"); // <-- Get the canvas context
let al = [];
for (let j = 0; j < bars.length; j++) {
al.push(0);
}
let start = 4.72;
let cw = 70;
let ch = 70;
let diff;
function progressSim(){
console.log(i);
diff = ((al[i] / 100) * Math.PI*2*10).toFixed(2);
ctx.clearRect(0, 0, cw, ch);
ctx.lineWidth = 10;
ctx.fillStyle = '#2F80ED';
ctx.strokeStyle = "#2F80ED";
ctx.textAlign = 'center';
ctx.font = '18px Roboto';
ctx.fillText(al[i], cw*.5, ch*.5+5, cw);
ctx.beginPath();
ctx.arc(35, 35, 30, start, diff/10+start, false);
ctx.stroke();
if(al[i] >= rating[i]){
clearTimeout(sim);
// Add scripting here that will run when progress completes
}
else {
al[i]++;
}
}
sim = setInterval(progressSim, 40);
}
}