Javascript 画布脚本不输出任何内容
在我看来,我做任何事情都是正确的。当页面加载时,我开始编写脚本,语法正常。我想问题是init函数没有加载,有人能指出我在哪里犯了错误吗Javascript 画布脚本不输出任何内容,javascript,canvas,Javascript,Canvas,在我看来,我做任何事情都是正确的。当页面加载时,我开始编写脚本,语法正常。我想问题是init函数没有加载,有人能指出我在哪里犯了错误吗 var canvas; var ctx; var x = 75; var y = 50; var r = 100; var width = 400; var height = 300; var drag = false; addEventListener("load",windowLoaded,f
var canvas;
var ctx;
var x = 75;
var y = 50;
var r = 100;
var width = 400;
var height = 300;
var drag = false;
addEventListener("load",windowLoaded,false);
function windowLoaded(){
init();
console.log("beertje");
}
function init() {
canvas = document.getElementById("canvas");
ctx = canvas.getContext("2d");
return setInterval(Circle, 10);
canvas.onmousedown = myDown;
canvas.onmouseup = myUp;
console.log("beertje");
}
function Circle(x,y,r) {
ctx.beginPath();
ctx.arc(x,y,r,0,Math.PI,true);
ctx.closePath();
ctx.fill();
}
function draw() {
clear();
arc(x,y,r,0,Math.PI,true);
ctx.fillStyle = "#444444";
arc(x - 15, y - 15, r, 0, Math.PI, true);
}
function myMove(e){
if (drag){
x = e.pageX - canvas.offsetLeft;
y = e.pageY - canvas.offsetTop;
}
}
function myDown(e){
if (e.pageX < x + 15 + canvas.offsetLeft && e.pageX > x - 15 +
canvas.offsetLeft && e.pageY < y + 15 + canvas.offsetTop &&
e.pageY > y -15 + canvas.offsetTop){
x = e.pageX - canvas.offsetLeft;
y = e.pageY - canvas.offsetTop;
drag = true;
canvas.onmousemove = myMove;
}
}
function myUp(){
drag = false;
canvas.onmousemove = null;
}
var画布;
var-ctx;
var x=75;
变量y=50;
var r=100;
var宽度=400;
var高度=300;
var-drag=false;
addEventListener(“加载”,windowLoaded,false);
函数windowLoaded(){
init();
控制台日志(“beertje”);
}
函数init(){
canvas=document.getElementById(“canvas”);
ctx=canvas.getContext(“2d”);
返回设置间隔(圆圈,10);
canvas.onmousedown=myDown;
canvas.onmouseup=myUp;
控制台日志(“beertje”);
}
函数圆(x,y,r){
ctx.beginPath();
弧(x,y,r,0,数学π,真);
ctx.closePath();
ctx.fill();
}
函数绘图(){
清除();
弧(x,y,r,0,数学π,真);
ctx.fillStyle=“#4444”;
弧(x-15,y-15,r,0,Math.PI,真);
}
函数myMove(e){
如果(拖动){
x=e.pageX-canvas.offsetLeft;
y=e.pageY-canvas.offsetTop;
}
}
函数myDown(e){
如果(e.pageXx-15+
canvas.offsetLeft&&e.pageYy-15+画布偏移){
x=e.pageX-canvas.offsetLeft;
y=e.pageY-canvas.offsetTop;
阻力=真;
canvas.onmousemove=myMove;
}
}
函数myUp(){
阻力=假;
canvas.onmousemove=null;
}
代码中的第一个问题是setInterval()
,它调用Circle()
,不带参数。尽管如此,还有全局的x
、y
和r
,这些都不是在Circle()
中定义的,因为其同名的参数将覆盖全局变量。()
但是,您可以将这些全局值传递给Circle()
,如下所示:
return setInterval(function () {
Circle(x, y, r);
}, 10);
但这是一个非常消耗内存的代码,因为同一个圆圈每秒绘制100次,在几分钟内屏幕上将出现大量圆圈。。。我建议您只使用EventHandler绘制圆圈,而不使用任何计时器
也不需要将此间隔返回到任何位置(除非这只是代码的一部分,并且windowload()
中有一个接收器)
由于“额外的”
return
,init()
中的eventhandler分配是无用的,因为上面的return
会将执行移回windowLoaded()
。因此,函数的其余部分将永远不会执行。我建议您将return
(目前没有用)或整行移到函数的末尾。Circle
函数有三个参数,但您没有传递任何参数:setInterval(Circle,10)代码>。另外,两个事件处理程序都不会被分配,return…
将切断init()
的执行。