我正在尝试创建一个简单的canvas游戏:
我在CodePen上有这段代码。
var canvas;
var ctx;
var x = 300;
var y = 400;
var r = 0;
var mx = 0;
var my = 0;
var WIDTH = 600;
var HEIGHT = 400;
function circle(x,y,r) {
ctx.fillStyle = "blue";
ctx.beginPath();
var text = Math.floor(Math.random()*10000);
var font = "bold " + (r*0.75) +"px serif";
var textWidth = ctx.measureText(text).width;
var textHeight = ctx.measureText("w").width;
ctx.arc(x, y, r, 0, Math.PI*2, true);
ctx.fill();
ctx.moveTo(50, 0);
ctx.lineTo(50, 10);
ctx.stroke();
ctx.moveTo(100, 0);
ctx.lineTo(100, 10);
ctx.stroke();
ctx.moveTo(150, 0);
ctx.lineTo(150, 10);
ctx.stroke();
ctx.fillStyle = "black"; // font color to write the text with
ctx.font = font;
ctx.fillText(text, x - (textWidth/2), y + (textHeight/2));
ctx.strokeStyle = '#000';
ctx.stroke();
}
function clear() {
ctx.clearRect(0, 0, WIDTH, HEIGHT);
}
function init() {
canvas = document.getElementById("canvas");
ctx = canvas.getContext("2d");
return setInterval(draw, 10);
}
function draw() {
clear();
circle(x, y, r);
if (y>=350){
y=y-0.5;
r=r+0.3;
}
if (y<=350){
y=y-1;
x=x-0.75;
}
if (y<=50){
x=x+0.75;
r=r-0.2;
}
}
<canvas id="canvas" width="600" height="400"></canvas>
<button id="test" onclick="return init()">test</button>
我的问题是:
我怎样能使数字在某个点停止?我使用随机函数来生成文本值。
我的按钮只能发射一次气泡,我使用了
setInterval
来启动动画。我想要的是发射另一个气泡,之前的气泡仍然会继续动画直到消失。
Uncaught IndexSizeError: Failed to execute 'arc' on 'CanvasRenderingContext2D': The radius provided (-0.2) is negative.
(第32行) - Siguza