Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <!doctype html>
- <html>
- <head>
- <meta charset="UTF-8" />
- <title>Canvas Test</title>
- </head>
- <body>
- <section>
- <div>
- <canvas id="canvas" width="300" height="200">
- This text is displayed if your browser does not support HTML5 Canvas.
- </canvas>
- </div>
- <script type="text/javascript">
- var canvas;
- var ctx;
- var dx = 5;
- var dy = 5;
- var x = 150;
- var y = 100;
- var WIDTH = 300;
- var HEIGHT = 200;
- function circle(x,y,r) {
- ctx.beginPath();
- ctx.arc(x, y, r, 0, Math.PI*2, true);
- ctx.fill();
- }
- function rect(x,y,w,h) {
- ctx.beginPath();
- ctx.rect(x,y,w,h);
- ctx.closePath();
- ctx.fill();
- ctx.stroke();
- }
- function clear() {
- ctx.clearRect(0, 0, WIDTH, HEIGHT);
- }
- function init() {
- canvas = document.getElementById("canvas");
- ctx = canvas.getContext("2d");
- return setInterval(draw, 10);
- }
- function doKeyDown(evt){
- switch (evt.keyCode) {
- case 38: /* Up arrow was pressed */
- if (y - dy > 0){
- y -= dy;
- }
- break;
- case 40: /* Down arrow was pressed */
- if (y + dy < HEIGHT){
- y += dy;
- }
- break;
- case 37: /* Left arrow was pressed */
- if (x - dx > 0){
- x -= dx;
- }
- break;
- case 39: /* Right arrow was pressed */
- if (x + dx < WIDTH){
- x += dx;
- }
- break;
- }
- }
- function draw() {
- ctx.fillStyle = "white";
- ctx.strokeStyle = "black";
- rect(0,0,WIDTH,HEIGHT);
- ctx.fillStyle="yellow";
- ctx.fillRect(0,0,20,20);
- ctx.fillStyle="red";
- ctx.fillRect(279,0,299,20);
- ctx.fillStyle="green";
- ctx.fillRect(0,179,20,199);
- ctx.fillStyle="blue";
- ctx.fillRect(279,179,299,199);
- ctx.fillStyle = "yellow";
- circle(x, y, 10);
- if(((x-dx)>=0 && (x-dx)<=20) && ((y-dy)>=0 && (y-dy)<=20) && !((((x+dx)>=279 && (x-+x)<=299) && ((y-dy)>=0 && (y-dy)<=20))
- &&(((x-dx)>=0 && (x-dx)<=20) && ((y+dy)>=179 && (y+dy)<=199)) && (((x+dx)>=279 && (x+dx)<=299) && ((y+dy)>=179 && (y+dy)<=199)))){
- ctx.fillStyle="yellow";
- circle(x,y,10);
- }
- if(((x+dx)>=279 && (x-+x)<=299) && ((y-dy)>=0 && (y-dy)<=20)){
- ctx.fillStyle="red";
- circle(x,y,10);
- }
- if(((x-dx)>=0 && (x-dx)<=20) && ((y+dy)>=179 && (y+dy)<=199)){
- ctx.fillStyle="green";
- circle(x,y,10);
- }
- if(((x+dx)>=279 && (x+dx)<=299) && ((y+dy)>=179 && (y+dy)<=199)){
- ctx.fillStyle="blue";
- circle(x,y,10);
- }
- }
- init();
- window.addEventListener('keydown',doKeyDown,true);
- </script>
- </section>
- </body>
- </html>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement