Canvas and objects - Javascript Canvas

Javascript examples for Canvas:Object

Description

Canvas and objects

Demo Code

ResultView the demo in separate window

<html>
   <head> 
      <meta name="viewport" content="width=device-width, initial-scale=1"> 
      <script type="text/javascript" src="https://code.jquery.com/jquery-1.9.1.js"></script> 
      <style id="compiled-css" type="text/css">

canvas {/*ww  w  .  j a  va 2 s. c  om*/
   border:1px solid red;
}


      </style> 
      <script type="text/javascript">
    $(window).load(function(){
        var canvas = document.getElementById("canvas");
        var ctx = canvas.getContext("2d");
        var canvasOffset = $("#canvas").offset();
        var offsetX = canvasOffset.left;
        var offsetY = canvasOffset.top;
        drawBallGroup();
        function drawBallGroup() {
            drawBall(8, 10, 5, "red");
            drawBall(20, 15, 10, "green");
            drawBall(25, 25, 8, "blue");
            drawBall(5, 22, 10, "orange");
            drawBall(18, 30, 10, "black");
        }
        function drawBall(x, y, radius, color) {
            ctx.beginPath();
            ctx.fillStyle = color;
            ctx.arc(x, y, radius, 0, 2 * Math.PI, false);
            ctx.fill();
        }
        function handleMouseDown(e) {
            mouseX = parseInt(e.clientX - offsetX);
            mouseY = parseInt(e.clientY - offsetY);

            ctx.clearRect(0, 0, canvas.width, canvas.height);

            ctx.translate(mouseX, mouseY);

            drawBallGroup();
            ctx.translate(-mouseX, -mouseY);
        }
        $("#canvas").mousedown(function (e) {
            handleMouseDown(e);
        });
    });

      </script> 
   </head> 
   <body> 
      <p>Click to move the ball group to a new location</p> 
      <p>WITHOUT recalculating each new ball position!</p> 
      <br> 
      <canvas id="canvas" width="350" height="300"></canvas>  
   </body>
</html>

Related Tutorials