click to draw circle and rectangle - Javascript Canvas

Javascript examples for Canvas:Circle

Description

click to draw circle and rectangle

Demo Code

ResultView the demo in separate window

<html lang="en">
   <head> 
      <title>Orbital Game</title> 
      <meta charset="utf-8"> 
      <link rel="stylesheet" href="css/index.css"> 
      <script src="js/index.js"></script> 
      <style>

body {//from ww  w.j av a  2  s .c o m
   font-family:monospace;
   color:white;
   background-color:#091D2C;
}
header {
   margin:0;
}
h1 {
   margin:0;
}
#canvas {
   border:1px solid black;
   background-color:cyan;
   box-shadow:0 0 5px 10px black;
   display:block;
   margin:auto;
}
td, th {
   border:2px solid white;
}
table {
   margin:auto;
}
td > input {
   width:60%;
}
#startbutton {
   height:95%;
   width:95%;
   border-radius:2px;
}
#vector {
   margin-top:-40px;
   margin-left:20px;
}

      </style> 
   </head> 
   <body> 
      <main> 
         <p>
            draw square? 
            <input type="checkbox" id="squareCheck">
         </p> 
         <canvas id="canvas" height="500px" width="800px"> 
         </canvas> 
         <br>
         <br> 
      </main> 
      <script>
addEventListener('load',init);
var mousepos = {
   x:0,
   y:0
}
var canvas, context;
function init() {
   canvas = document.querySelector('canvas');
   context = canvas.getContext('2d');
   canvas.addEventListener('mousemove',showMouse);
   canvas.addEventListener('click',function() {
      if (!document.querySelector('#squareCheck').checked) {
      drawCircle(mousepos.x,mousepos.y,30,'red',context);
      } else {
        drawSquare(mousepos.x,mousepos.y,30,30,'blue',context)
      }
   });
   console.log('page ready');
}
function showMouse(evt) {
   mousepos=getlocalcoord(evt);
}
function drawCircle(x,y,rad,col,ctx){
   ctx.save();
   ctx.translate(x,y);
   ctx.beginPath();
   ctx.arc(0,0,rad,0,2*Math.PI,false);
   ctx.fillStyle='red';
   ctx.fill();
   ctx.restore();
  ctx.closePath();
}
function drawSquare(x,y,w,h,col,ctx) {
   ctx.save();
   ctx.translate(x,y);
   ctx.beginPath();
   ctx.fillStyle=col;
   ctx.fillRect(0,0,w,h);
   ctx.fill();
   ctx.restore();
  ctx.closePath();
}
function getlocalcoord(evt) {
   var rect=evt.target.getBoundingClientRect();
   mousepos = {
      x:Math.floor(evt.clientX-rect.left),
      y:Math.floor(evt.clientY-rect.top)
   }
   return mousepos
}

      </script>  
   </body>
</html>

Related Tutorials