简体   繁体   English

无法清除HTML / JavaScript画布

[英]Cannot clear HTML/Javascript canvas

Here is my javascript code: 这是我的JavaScript代码:

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. 函数clearparticles是我尝试清除画布上的html / javascript粒子的地方。 However this doesn't seem to be working at all. 但是,这似乎根本不起作用。 It seems I get the following error: Cannot read property 'clearRect' of undefined 看来我收到以下错误: 无法读取未定义的属性'clearRect'

I cannot think of anything else to get it working. 我想不出什么办法使它起作用。 What am I doing wrong? 我究竟做错了什么?

EDIT: Here is the HTML CODE (test code): 编辑:这是HTML代码(测试代码):

<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 您的HTML代码包含

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

When you click that button, it invokes the method clearparticles() . 当您单击该按钮时,它将调用方法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. 该函数需要一个参数,但是您不提供onclick事件中的任何数据。 You can solve it by removing the "content" argument. 您可以通过删除“ content”参数来解决它。 To clear the rectangle, you only have to call the clearRect(...) function of your drawing context (more info: MDN - CanvasRenderingContext2D ) 要清除矩形,只需调用图形上下文的clearRect(...)函数(更多信息: 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. 或者,您当然可以在onclick属性中提供一个参数。 But that is not a clean solution. 但这不是一个干净的解决方案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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