简体   繁体   中英

Cannot clear HTML/Javascript canvas

Here is my javascript code:

canvas = document.getElementById("canvas");
context = canvas.getContext("2d");
width = canvas.width = window.innerWidth;
height = canvas.height = window.innerHeight;


 particle = [];
 particleCount = 0,
gravity = 0.3,
colors = [
  '#f44336', '#e91e63', '#9c27b0', '#673ab7', '#3f51b5',
  '#2196f3', '#03a9f4', '#00bcd4', '#009688', '#4CAF50',
  '#8BC34A', '#CDDC39', '#FFEB3B', '#FFC107', '#FF9800',
  '#FF5722', '#795548'
];


function drawparticles(){
        for( var i = 0; i < 250; i++){


particle.push({
    x : width/2,
    y : height/2,
    boxW : randomRange(5,15),
    boxH : randomRange(5,15),
    size : randomRange(2,6),

    spikeran:randomRange(3,5),

    velX :randomRange(-8,8),
    velY :randomRange(-50,-10),

    angle :convertToRadians(randomRange(0,360)),
    color:colors[Math.floor(Math.random() * colors.length)],
    anglespin:randomRange(-0.2,0.2),

    draw : function(){


        context.save();
            context.translate(this.x,this.y);
            context.rotate(this.angle);
        context.fillStyle=this.color;
        context.beginPath();
        // drawStar(0, 0, 5, this.boxW, this.boxH);
    context.fillRect(this.boxW/2*-1,this.boxH/2*-1,this.boxW,this.boxH);
        context.fill();
                context.closePath();
        context.restore();
        this.angle += this.anglespin;
        this.velY*= 0.999;
        this.velY += 0.3;

        this.x += this.velX;
        this.y += this.velY;
            if(this.y < 0){
        this.velY *= -0.2;
            this.velX *= 0.9;
        };
        if(this.y > height){
        this.anglespin = 0;
        this.y = height;
        this.velY *= -0.2;
            this.velX *= 0.9;
        };
            if(this.x > width ||this.x< 0){

        this.velX *= -0.5;
        };



    },




    });


   }


}



function drawScreen(){

for( var i = 0; i < particle.length; i++){
    particle[i].draw();

}


}



function update(){

    var fps = 120;

    context.clearRect(0,0,width,height);
    drawScreen();

    setTimeout(function() {
        requestAnimationFrame(update);
    }, 1000 / fps);
}

update();

 function clearparticles(content){
    content.clearRect(0, 0, canvas.width, canvas.height);
 }

 function randomRange(min, max){
    return min + Math.random() * (max - min );
 }

 function randomInt(min, max){
    return Math.floor(min + Math.random()* (max - min + 1));
 }

function convertToRadians(degree) {
    return degree*(Math.PI/180);
 }

The function clearparticles is where I try to clear the html/javascript particles on my canvas. However this doesn't seem to be working at all. It seems I get the following error: Cannot read property 'clearRect' of undefined

I cannot think of anything else to get it working. What am I doing wrong?

EDIT: Here is the HTML CODE (test code):

<style>
    html, body  {
        padding:0;
        margin:0;
          width: 100%;
          height: 100%;
          cursor: default;   text-align: center;

          font-family: 'PT Sans', sans-serif;
    }

    canvas  {
                        pointer-events:none;
                position: absolute;
                left:0;
                top:0;
                z-index:0;
                border:0px solid #000;
    }
</style>
        <script src="http://code.jquery.com/jquery-1.9.0.min.js"></script>

   </head>
     <body>
        <canvas id="canvas"></canvas>
         <script language="javascript" type="text/javascript" src="confetti2.js"></script>
     <button onclick="drawparticles()">Spawn</button>
      <button onclick="clearparticles()">Clear</button>

  </body>

    </html>

Your HTML code contains

 <button onclick="clearparticles()">Clear</button>

When you click that button, it invokes the method clearparticles() . But that doesn't exist. It is not able to find that function. What you have is

function clearparticles(content){
    content.clearRect(0, 0, canvas.width, canvas.height);
}

This function expects an argument, but you don't provide any data from the onclick event. You can solve it by removing the "content" argument. To clear the rectangle, you only have to call the clearRect(...) function of your drawing context (more info: MDN - CanvasRenderingContext2D )

Since you already have a context as global variable,

context = canvas.getContext("2d");

You can simply use the next to solve your problem

function clearparticles(){
    context.clearRect(0, 0, canvas.width, canvas.height);
}

Or you can of course provide an argument in the onclick attribute. But that is not a clean solution.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM