Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <!DOCTYPE html>
- <html>
- <head>
- <title>HTML5 Canvas</title>
- <style type="text/css">
- * {
- background-color: black;
- border-color: #00ff00;
- color: #00ff00;
- }
- </style>
- <script type="text/javascript">
- var x = 0;
- var y = 0;
- var xdir = 1;
- var ydir = 1;
- var cw = 800;
- var ch = 500;
- var speed = 1;
- var lpos = 250;
- var rpos = 250;
- var pw = 20;
- var ph = 100;
- var bw = 36;
- var bh = 36;
- var lscore = 0;
- var rscore = 0;
- function setup(){
- var c = document.getElementById( "Animation" );
- var ctx = c.getContext( "2d" );
- ctx.fillStyle = "#00ff00";
- ctx.fillRect( 0, ch/2-ph/2, pw, ph );
- ctx.fillRect( cw-pw, ch/2-ph/2, pw, ph );
- animate();
- }
- function stop(){
- if( xdir ) lscore++;
- else rscore++;
- refresh();
- }
- function refresh(){
- cw = document.getElementById( "cw" ).value;
- ch = document.getElementById( "ch" ).value;
- speed = document.getElementById( "speed" ).value;
- var c = document.getElementById( "Animation" );
- document.getElementById( "lscore" ).innerHTML = lscore;
- document.getElementById( "rscore" ).innerHTML = rscore;
- c.width = String( cw );
- c.height = String( ch );
- x = 0;
- y = 0;
- xdir = 1;
- ydir = 1;
- }
- function animate(){
- var c = document.getElementById( "Animation" );
- var ctx = c.getContext( "2d" );
- ctx.fillStyle = "#00ff00";
- ctx.clearRect( x, y, bw, bh );
- if( xdir ) x += 2;
- else x -= 2;
- if( ydir ) y += 2;
- else y -= 2;
- if( xdir ){ // traveling right
- if( y+bw > rpos - ph/2 && y < rpos + ph/2 ){ // in range of rpaddle
- if( x+bw+pw >= cw ){ xdir = 0; }
- }
- else{
- if( x+bw >= cw ) stop();
- }
- }
- else{ // traveling left
- if( y+bw > lpos - ph/2 && y < lpos + ph/2 ){ // in range of lpaddle
- if( x-pw <= 0 ){ xdir = 1; }
- }
- else{
- if( x <= 0 ) stop();
- }
- }
- ctx.fillRect( x, y, bw, bh );
- if( Math.abs( y - ch ) <= bh ) ydir = 0;
- if( Math.abs( y ) <= 0 ) ydir = 1;
- window.setTimeout( animate, 20/speed );
- }
- </script>
- </head>
- <body onload="setup();">
- <center><table><tr><td>
- <canvas id="Animation" width="800" height="500" style="border: 1px solid #00ff00;"></canvas>
- <h2>Controls:</h2>
- <table>
- <col></col><col></col>
- <col width="200"></col>
- <col></col><col></col>
- <thead>
- <th colspan="2"><h2>Controls:</h2></th>
- <th></th>
- <th colspan="2"><h2>Scores:</h2></th>
- </head>
- <tr><td>Speed:</td><td><input id="speed" type="text" value="1"></td><td></td><td>Left:</td><td><span id="lscore">0</span></td></tr>
- <tr><td>Container width:</td><td><input id="cw" type="text" value="800"></td><td></td><td>Right:</td><td><span id="rscore">0</span></td></tr>
- <tr><td>Container height:</td><td><input id="ch" type="text" value="500"></td></tr>
- </table>
- <button onclick="refresh();">Refresh</button>
- </td></tr></table>
- </body>
- </html>
Add Comment
Please, Sign In to add comment