我设计了一个带有canvas的计数器。在设计中一切都很顺利但是当我想更改时间数并通过setInterval刷新它时,filltext start会自行创建并改变它的位置。 代码示例在这里:
<canvas id="top-left" width="300" height="300"></canvas>
<script>
var canvas = document.getElementById("top-left");
var ctx = canvas.getContext("2d");
ctx.beginPath();
ctx.moveTo(canvas.width * 0.97,canvas.height * 0.06);
ctx.lineTo(canvas.width * 0.97,canvas.height * 0.97);
ctx.arc(canvas.width * 0.97,canvas.height * 0.97,canvas.width * 0.91,1*Math.PI,1.5*Math.PI);
ctx.moveTo(canvas.width * 0.97,canvas.height * 0.97);
ctx.lineTo(canvas.width * 0.06,canvas.height * 0.97);
ctx.shadowBlur = canvas.width * 0.016;
ctx.shadowOffsetX = canvas.width * 0.016;
ctx.shadowColor = "#666666";
ctx.fillStyle = "#98ae32";
ctx.fill();
ctx.lineWidth = canvas.width * 0.01;
ctx.lineCap = "round";
ctx.strokeStyle = "#000000";
ctx.stroke();
var x = 1;
var c = setInterval(function(){
ctx.font = canvas.width * 0.273 + "px Baskerville Old Face";
ctx.fillStyle = "#000000";
ctx.fillText(x,canvas.width * 0.33,canvas.height * 0.86);
x++;
if(x === 5){
clearInterval(c);
}
},1000);
</script>
我想知道如何更改filltext文本而不创建自己。我只想更新文本。请帮我解决我的问题。 谢谢
答案 0 :(得分:0)
如何在圆弧上绘制一组单词
首先使您的代码可重复使用:
var texts=['Hello','World','Coding','is','Fun!'];
然后创建一个执行以下操作的动画循环:
以下是示例代码和演示:
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var cw=canvas.width;
var ch=canvas.height;
var i=0;
var texts=['Hello','World','Coding','is','Fun!'];
var nextTime=0;
var duration=1000;
requestAnimationFrame(animate);
function animate(time){
if(time<nextTime){ requestAnimationFrame(animate); return;}
nextTime+=duration;
ctx.clearRect(0,0,cw,ch);
drawArc();
drawText(texts[i]);
i++;
if(i<texts.length){ requestAnimationFrame(animate); }
}
function drawText(text){
var px=canvas.width*0.273;
ctx.font = px + "px Baskerville Old Face";
ctx.textAlign='right';
ctx.fillStyle = "#000000";
ctx.fillText(text,canvas.width-15,canvas.height * 0.86);
}
function drawArc(){
ctx.beginPath();
ctx.moveTo(canvas.width * 0.97,canvas.height * 0.06);
ctx.lineTo(canvas.width * 0.97,canvas.height * 0.97);
ctx.arc(canvas.width * 0.97,canvas.height * 0.97,canvas.width * 0.91,1*Math.PI,1.5*Math.PI);
ctx.moveTo(canvas.width * 0.97,canvas.height * 0.97);
ctx.lineTo(canvas.width * 0.06,canvas.height * 0.97);
ctx.shadowBlur = canvas.width * 0.016;
ctx.shadowOffsetX = canvas.width * 0.016;
ctx.shadowColor = "#666666";
ctx.fillStyle = "#98ae32";
ctx.fill();
ctx.lineWidth = canvas.width * 0.01;
ctx.lineCap = "round";
ctx.strokeStyle = "#000000";
ctx.stroke();
}
&#13;
body{ background-color: ivory; }
#canvas{border:1px solid red; margin:0 auto; }
&#13;
<canvas id="canvas" width=175 height=175></canvas>
&#13;