clearRect不工作 [英] clearRect not working

查看:377
本文介绍了clearRect不工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在javascript做一个乒乓球游戏,以学习制作游戏,我想让它面向对象。



我不能得到 clearRect 工作。它所做的就是画一条长得更长的线。
下面是相关代码:

  function Ball(){
this.radius = 5;
this.Y = 20;
this.X = 25;
this.draw = function(){
ctx.arc(this.X,this.Y,this.radius,0,Math.PI * 2,true);
ctx.fillStyle ='#00ff00';
ctx.fill();
};
}

var ball = new Ball();

function draw(){
player.draw();
ball.draw();
}

function update(){
ctx.clearRect(0,0,800,400);
draw();
ball.X ++;
}



我试图把 ctx.clearRect 部分在 draw() t工作。
我也尝试了 fillRect 与白色,但它给出相同的结果。
我如何解决这个问题?

解决方案

$ b



在绘制圆圈之前添加 ctx.beginPath()
$ b

jsFiddle



此外,提示...




  • 您的资产不应负责绘制自己(他们的 draw $ c> method)。相反,也许定义他们的视觉属性(是一个圆?半径?),让你的主要渲染函数处理 canvas 特定的绘图(这也有优点,

  • 而不是 setInterval(),请使用 requestAnimationFrame() 。支持目前不是那么好,所以你可能想要使用 setInterval()或递归 setTimeout() c> pattern。

  • 您的 clearRect() $ c>元素(或将它们定义在某处)。将它们包含在渲染函数中类似于魔术数字,可能会导致维护问题进一步向下。


I'm doing a Pong game in javascript in order to learn making games, and I want to make it object oriented.

I can't get clearRect to work. All it does is draw a line that grows longer. Here is the relevant code:

function Ball(){
    this.radius = 5;
    this.Y = 20;
    this.X = 25;
    this.draw = function() {
        ctx.arc(this.X, this.Y, this.radius, 0, Math.PI*2, true);
        ctx.fillStyle = '#00ff00';
        ctx.fill();
    };
}

var ball = new Ball();

function draw(){
    player.draw();
    ball.draw();
}

function update(){
    ctx.clearRect(0, 0, 800, 400);
    draw();
    ball.X++;
}

I've tried to put the ctx.clearRect part in the draw() and ball.draw() functions and it doesn't work. I also tried fillRect with white but it gives the same results. How can I fix this?

解决方案

Your real problem is you are not closing your circle's path.

Add ctx.beginPath() before you draw the circle.

jsFiddle.

Also, some tips...

  • Your assets should not be responsible for drawing themselves (their draw() method). Instead, perhaps define their visual properties (is it a circle? radius?) and let your main render function handle canvas specific drawing (this also has the advantage that you can switch your renderer to regular DOM elements or WebGL further down the track easily).
  • Instead of setInterval(), use requestAnimationFrame(). Support is not that great at the moment so you may want to shim its functionality with setInterval() or the recursive setTimeout() pattern.
  • Your clearRect() should be passed the dimensions from the canvas element (or have them defined somewhere). Including them in your rendering functions is akin to magic numbers and could lead to a maintenance issue further down the track.

这篇关于clearRect不工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆