如何刷新HTML包上的Canvas? [英] How to refresh a Canvas on a HTML bag?

查看:97
本文介绍了如何刷新HTML包上的Canvas?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个JavaScript程序,在屏幕上绘制了一百个圈子,他们可以在画布上自己弹奏。目前我在他们身上绘制一个空矩形来清除下一代。但有没有更好的方法来擦除和刷新HTML页面上的Canvas。



代码:

  function drawScreen(){
context.fillStyle ='#EEEEEE';
context.fillRect(0,0,theCanvas.width,theCanvas.height);
// Box
context.strokeStyle ='#000000';
context.strokeRect(1,1,theCanvas.width-2,theCanvas.height-2);

update();
testWalls();
collide();
render();

$ / code>

以下是所有代码,如果您想尝试它:

 <!doctype html> 
< html lang =en>
< head>
< meta charset =UTF-8>
< title> CH5EX7:简单交互的球< / title>
< script type =text / javascript>
window.addEventListener('load',eventWindowLoaded,false);
函数eventWindowLoaded(){
canvasApp();
}

函数canvasApp(){
var numBalls = 200;
var maxSize = 15;
var minSize = 5;
var maxSpeed = maxSize + 5;
var balls = new Array();
var tempBall;
var tempX;
var tempY;
var tempSpeed;
var tempAngle;
var tempRadius;
var tempRadians;
var tempvelocityx;
var tempvelocityy;

函数drawScreen(){
context.fillStyle ='#EEEEEE';
context.fillRect(0,0,theCanvas.width,theCanvas.height);
// Box
context.strokeStyle ='#000000';
context.strokeRect(1,1,theCanvas.width-2,theCanvas.height-2);

update();
testWalls();
collide();
render();
}

函数update(){
var ball;
for(var i = 0; i< balls.length; i ++){
ball = balls [i];
ball.nextx =(ball.x + = ball.velocityx);
ball.nexty =(ball.y + = ball.velocityy);



function testWalls(){
var ball;
var testBall;

for(var i = 0; i< balls.length; i ++){
ball = balls [i];

if(ball.nextx + ball.radius> theCanvas.width){
ball.velocityx = ball.velocityx * -1;
ball.nextx = theCanvas.width - ball.radius;

} else if(ball.nextx-ball.radius< 0){
ball.velocityx = ball.velocityx * -1;
ball.nextx = ball.radius;

} else if(ball.nexty + ball.radius> theCanvas.height){
ball.velocityy = ball.velocityy * -1;
ball.nexty = theCanvas.height - ball.radius;

} else if(ball.nexty-ball.radius< 0){
ball.velocityy = ball.velocityy * -1;
ball.nexty = ball.radius;




function render(){
var ball;
context.fillStyle =#000000;
for(var i = 0; i< balls.length; i ++){
ball = balls [i];
ball.x = ball.nextx;
ball.y = ball.nexty;

context.beginPath();
context.arc(ball.x,ball.y,ball.radius,0,Math.PI * 2,true);
context.closePath();
context.fill();
}
}

函数collide(){
var ball;
var testBall;
for(var i = 0; i< balls.length; i ++){
ball = balls [i]; (var j = i + 1; j testBall = balls [j];
if(hitTestCircle(ball,testBall)){
collideBalls(ball,testBall);




$ b function hitTestCircle(ball1,ball2){
var retval = false;
var dx = ball1.nextx - ball2.nextx;
var dy = ball1.nexty - ball2.nexty;
var distance =(dx * dx + dy * dy);
if(distance <=(ball1.radius + ball2.radius)*(ball1.radius + ball2.radius)){
retval = true;
}
return retval;
}

函数collideBalls(ball1,ball2){
var dx = ball1.nextx - ball2.nextx;
var dy = ball1.nexty - ball2.nexty;

var collisionAngle = Math.atan2(dy,dx);

var speed1 = Math.sqrt(ball1.velocityx * ball1.velocityx + ball1.velocityy * ball1.velocityy);
var speed2 = Math.sqrt(ball2.velocityx * ball2.velocityx + ball2.velocityy * ball2.velocityy);

var direction1 = Math.atan2(ball1.velocityy,ball1.velocityx);
var direction2 = Math.atan2(ball2.velocityy,ball2.velocityx);

var velocityx_1 = speed1 * Math.cos(direction1 - collisionAngle);
var velocityy_1 = speed1 * Math.sin(direction1 - collisionAngle);
var velocityx_2 = speed2 * Math.cos(direction2 - collisionAngle);
var velocityy_2 = speed2 * Math.sin(direction2 - collisionAngle);

var final_velocityx_1 =((ball1.mass - ball2.mass)* velocityx_1 +(ball2.mass + ball2.mass)* velocityx_2)/(ball1.mass + ball2.mass);
var final_velocityx_2 =((ball1.mass + ball1.mass)* velocityx_1 +(ball2.mass - ball1.mass)* velocityx_2)/(ball1.mass + ball2.mass);

var final_velocityy_1 = velocityy_1;
var final_velocityy_2 = velocityy_2;

ball1.velocityx = Math.cos(collisionAngle)* final_velocityx_1 + Math.cos(collisionAngle + Math.PI / 2)* final_velocityy_1;
ball1.velocityy = Math.sin(collisionAngle)* final_velocityx_1 + Math.sin(collisionAngle + Math.PI / 2)* final_velocityy_1;
ball2.velocityx = Math.cos(collisionAngle)* final_velocityx_2 + Math.cos(collisionAngle + Math.PI / 2)* final_velocityy_2;
ball2.velocityy = Math.sin(collisionAngle)* final_velocityx_2 + Math.sin(collisionAngle + Math.PI / 2)* final_velocityy_2;

ball1.nextx =(ball1.nextx + = ball1.velocityx);
ball1.nexty =(ball1.nexty + = ball1.velocityy);
ball2.nextx =(ball2.nextx + = ball2.velocityx);
ball2.nexty =(ball2.nexty + = ball2.velocityy);
}

theCanvas = document.getElementById('canvasOne');
context = theCanvas.getContext('2d'); (var i = 0; i tempRadius = 5;


var placeOK = false;
while(!placeOK){
tempX = tempRadius * 3 +(Math.floor(Math.random()* theCanvas.width)-tempRadius * 3);
tempY = tempRadius * 3 +(Math.floor(Math.random()* theCanvas.height)-tempRadius * 3);
tempSpeed = 4;
tempAngle = Math.floor(Math.random()* 360);
tempRadians = tempAngle * Math.PI / 180;
tempvelocityx = Math.cos(tempRadians)* tempSpeed;
tempvelocityy = Math.sin(tempRadians)* tempSpeed;
$ b tempBall = {x:tempX,y:tempY,nextX:tempX,nextY:tempY,radius:tempRadius,speed:tempSpeed,angle:tempAngle,velocityx:tempvelocityx,velocityy:tempvelocityy,mass:tempRadius };
placeOK = canStartHere(tempBall);
}
balls.push(tempBall);
}

函数canStartHere(ball){
var retval = true;
for(var i = 0; i< balls.length; i ++){
if(hitTestCircle(ball,balls [i])){
retval = false;
}
}
return retval;
}
函数gameLoop(){
window.setTimeout(gameLoop,20);
drawScreen()
}

gameLoop();


}

< / script>

< / head>
< body>
< div style =position:absolute; top:50px; left:50px;>

< canvas id =canvasOnewidth =500height =500>
您的浏览器不支持HTML 5画布。
< / canvas>
< / div>

< / body>
< / html>

我在这里放置了最新的工作代码,以防有人看着这篇文章作为参考路。



代码:

 <!doctype html> 
< html lang =en>
< head>
< meta charset =UTF-8>
< title>移入圈子< /标题>
< script type =text / javascript>
window.addEventListener('load',eventWindowLoaded,false);
函数eventWindowLoaded(){
canvasApp();

}

函数canvasApp(){
var radius = 100;
var circle = {centerX:250,centerY:250,radius:125,angle:0}
var ball = {x:0,y:0,speed:.1};

theCanvas = document.getElementById('canvasOne');
context = theCanvas.getContext('2d');

函数erraseCanvas(){
context.clearRect(0,0,theCanvas.width,theCanvas.height);
}

函数drawScreen(){
erraseCanvas();

ball.x = circle.centerX + Math.cos(circle.angle)* circle.radius;
ball.y = circle.centerY + Math.sin(circle.angle)* circle.radius;
circle.angle + = ball.speed;

context.fillStyle =#000000;
context.beginPath();
context.arc(ball.x,ball.y,15,0,Math.PI * 2,true);
context.closePath();
context.fill();
}

函数gameLoop(){
window.setTimeout(gameLoop,20);
drawScreen()
}

gameLoop();
}

< / script>

< / head>
< body>
< div style =position:absolute; top:50px; left:50px;>

< canvas id =canvasOnewidth =500height =500>
您的浏览器不支持HTML 5画布。
< / canvas>
< / div>

< / body>
< / html>


解决方案

调整画布大小会使画布清除。

  myCanvasElement.width + = 0; / /导致画布调整大小(大小相同)

被警告这也会清除您的转换

I have this javascript program that draws a hundred circles on the screen and they can bounce around in the canvas on themselves. Currently I draw an empty rectangle over them to erase next generation of them. But is there a better way to erase and refresh a Canvas on a HTML page.

Code:

    function  drawScreen () {
    context.fillStyle = '#EEEEEE';
    context.fillRect(0, 0, theCanvas.width, theCanvas.height);
    //Box
    context.strokeStyle = '#000000'; 
    context.strokeRect(1,  1, theCanvas.width-2, theCanvas.height-2);

    update();
    testWalls();
    collide();
    render();
}

Here is all of the code if you want to try it:

<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>CH5EX7: Balls With Simple Interactions</title>
<script type="text/javascript">
window.addEventListener('load', eventWindowLoaded, false);  
function eventWindowLoaded() {
    canvasApp();
}

function canvasApp() {
    var numBalls = 200 ;
    var maxSize = 15;
    var minSize = 5;
    var maxSpeed = maxSize+5;
    var balls = new Array();
    var tempBall;
    var tempX;
    var tempY;
    var tempSpeed;
    var tempAngle;
    var tempRadius;
    var tempRadians;
    var tempvelocityx;
    var tempvelocityy;

    function  drawScreen () {
        context.fillStyle = '#EEEEEE';
        context.fillRect(0, 0, theCanvas.width, theCanvas.height);
        //Box
        context.strokeStyle = '#000000'; 
        context.strokeRect(1,  1, theCanvas.width-2, theCanvas.height-2);

        update();
        testWalls();
        collide();
        render();
    }

    function update() {
        var ball;
        for (var i =0; i <balls.length; i++) {
            ball = balls[i];
            ball.nextx = (ball.x += ball.velocityx);
            ball.nexty = (ball.y += ball.velocityy);
        }
    }

    function testWalls() {
        var ball;
        var testBall;

        for (var i =0; i <balls.length; i++) {
            ball = balls[i];

            if (ball.nextx+ball.radius > theCanvas.width) {
                ball.velocityx = ball.velocityx*-1;
                ball.nextx = theCanvas.width - ball.radius;

            } else if (ball.nextx-ball.radius < 0 ) {
                ball.velocityx = ball.velocityx*-1;
                ball.nextx =  ball.radius;

            } else if (ball.nexty+ball.radius > theCanvas.height ) {
                ball.velocityy = ball.velocityy*-1;
                ball.nexty = theCanvas.height - ball.radius;

            } else if(ball.nexty-ball.radius < 0) {
                ball.velocityy = ball.velocityy*-1;
                ball.nexty =  ball.radius;
            }
        }
    }

    function render() {
        var ball;
        context.fillStyle = "#000000";
        for (var i =0; i <balls.length; i++) {
            ball = balls[i];
            ball.x = ball.nextx;
            ball.y = ball.nexty;

            context.beginPath();
            context.arc(ball.x,ball.y,ball.radius,0,Math.PI*2,true);
            context.closePath();
            context.fill();
        }
    }

    function collide() {
        var ball;
        var testBall;
        for (var i =0; i <balls.length; i++) {
            ball = balls[i];
            for (var j = i+1; j < balls.length; j++) {
                testBall = balls[j];
                if (hitTestCircle(ball,testBall)) {
                    collideBalls(ball,testBall);
                 }
            }
        }
    }

    function hitTestCircle(ball1,ball2) {
        var retval = false;
        var dx = ball1.nextx - ball2.nextx;
        var dy = ball1.nexty - ball2.nexty;
        var distance = (dx * dx + dy * dy);
        if (distance <= (ball1.radius + ball2.radius) * (ball1.radius + ball2.radius) ) {
              retval = true;
        }
        return retval;
    }

    function collideBalls(ball1,ball2) {
        var dx = ball1.nextx - ball2.nextx;
        var dy = ball1.nexty - ball2.nexty;

        var collisionAngle = Math.atan2(dy, dx);

        var speed1 = Math.sqrt(ball1.velocityx * ball1.velocityx + ball1.velocityy * ball1.velocityy);
        var speed2 = Math.sqrt(ball2.velocityx * ball2.velocityx + ball2.velocityy * ball2.velocityy);

        var direction1 = Math.atan2(ball1.velocityy, ball1.velocityx);
        var direction2 = Math.atan2(ball2.velocityy, ball2.velocityx);

        var velocityx_1 = speed1 * Math.cos(direction1 - collisionAngle);
        var velocityy_1 = speed1 * Math.sin(direction1 - collisionAngle);
        var velocityx_2 = speed2 * Math.cos(direction2 - collisionAngle);
        var velocityy_2 = speed2 * Math.sin(direction2 - collisionAngle);

        var final_velocityx_1 = ((ball1.mass - ball2.mass) * velocityx_1 + (ball2.mass + ball2.mass) * velocityx_2)/(ball1.mass + ball2.mass);
        var final_velocityx_2 = ((ball1.mass + ball1.mass) * velocityx_1 + (ball2.mass - ball1.mass) * velocityx_2)/(ball1.mass + ball2.mass);

        var final_velocityy_1 = velocityy_1;
        var final_velocityy_2 = velocityy_2;

        ball1.velocityx = Math.cos(collisionAngle) * final_velocityx_1 + Math.cos(collisionAngle + Math.PI/2) * final_velocityy_1;
        ball1.velocityy = Math.sin(collisionAngle) * final_velocityx_1 + Math.sin(collisionAngle + Math.PI/2) * final_velocityy_1;
        ball2.velocityx = Math.cos(collisionAngle) * final_velocityx_2 + Math.cos(collisionAngle + Math.PI/2) * final_velocityy_2;
        ball2.velocityy = Math.sin(collisionAngle) * final_velocityx_2 + Math.sin(collisionAngle + Math.PI/2) * final_velocityy_2;

        ball1.nextx = (ball1.nextx += ball1.velocityx);
        ball1.nexty = (ball1.nexty += ball1.velocityy);
        ball2.nextx = (ball2.nextx += ball2.velocityx);
        ball2.nexty = (ball2.nexty += ball2.velocityy);
    }

    theCanvas = document.getElementById('canvasOne');
    context = theCanvas.getContext('2d');

    for (var i = 0; i < numBalls; i++) {
        tempRadius = 5;
        var placeOK = false;
        while (!placeOK) {
            tempX = tempRadius*3 + (Math.floor(Math.random()*theCanvas.width)-tempRadius*3);
            tempY = tempRadius*3 + (Math.floor(Math.random()*theCanvas.height)-tempRadius*3);
            tempSpeed = 4;
            tempAngle =  Math.floor(Math.random()*360);
            tempRadians = tempAngle * Math.PI/ 180;
            tempvelocityx = Math.cos(tempRadians) * tempSpeed;
            tempvelocityy = Math.sin(tempRadians) * tempSpeed;

            tempBall = {x:tempX,y:tempY, nextX: tempX, nextY: tempY, radius:tempRadius, speed:tempSpeed, angle:tempAngle, velocityx:tempvelocityx, velocityy:tempvelocityy, mass:tempRadius};
            placeOK = canStartHere(tempBall);
        }
        balls.push(tempBall);
    }

    function canStartHere(ball) {
        var retval = true;
        for (var i =0; i <balls.length; i++) {
            if (hitTestCircle(ball, balls[i])) {
                retval = false;
            }
        }
        return retval;
    }
   function gameLoop() {
            window.setTimeout(gameLoop, 20);
            drawScreen()    
        }

    gameLoop();


}

</script>

</head>
<body> 
<div style="position: absolute; top: 50px; left: 50px;">

<canvas id="canvasOne" width="500" height="500">
 Your browser does not support the HTML 5 Canvas. 
</canvas>
</div>

</body>
</html>

I have placed the newest working code here in case someone is looking at this post as a reference down the road. The clear the canvas is down differently and works very well.

Code:

<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Moving In Circle</title>
<script type="text/javascript">
window.addEventListener('load', eventWindowLoaded, false);  
function eventWindowLoaded() {
    canvasApp();

}

 function canvasApp() {
    var radius = 100;
    var circle = {centerX:250, centerY:250, radius:125, angle:0}
    var ball = {x:0, y:0,speed:.1};

    theCanvas = document.getElementById('canvasOne');
    context = theCanvas.getContext('2d');

    function erraseCanvas() {
        context.clearRect(0,0,theCanvas.width,theCanvas.height);
    }

    function drawScreen () {
        erraseCanvas();

        ball.x = circle.centerX + Math.cos(circle.angle) * circle.radius;
        ball.y = circle.centerY + Math.sin(circle.angle) * circle.radius;
        circle.angle += ball.speed;

        context.fillStyle = "#000000";
        context.beginPath();
            context.arc(ball.x,ball.y,15,0,Math.PI*2,true);
        context.closePath();
        context.fill();
    }

    function gameLoop() {
         window.setTimeout(gameLoop, 20);
         drawScreen()   
    }

    gameLoop();
}

</script>

</head>
<body>  
<div style="position: absolute; top: 50px; left: 50px;">

<canvas id="canvasOne" width="500" height="500">
 Your browser does not support the HTML 5 Canvas. 
</canvas>
</div>

</body>
</html>

解决方案

Resizing the canvas will cause the canvas to get cleared.

myCanvasElement.width+=0; // causes the canvas to resize (to the same size)

Be warned this will also clear your transformations

这篇关于如何刷新HTML包上的Canvas?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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