draw a line in canvas with a background image - Javascript Canvas

Javascript examples for Canvas:image

Description

draw a line in canvas with a background image

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">

body {/*from  www . j  av a 2 s.co  m*/
   background-color: #666;
}
canvas {
   border:1px solid red;
}


      </style> 
      <script type="text/javascript">
    $(window).load(function(){
        var canvas = document.getElementById("canvas");
        var ctx = canvas.getContext("2d");
        window.requestAnimFrame = (function (callback) {
            return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame || function (callback) {
                window.setTimeout(callback, 1000 / 60);
            };
        })();
        var radius = 50;
        var x = 100;
        var dx = 10;
        var y = 100;
        var dy = 10;
        var delay = 10;
        var img = new Image();
        img.onload = function () {
            var canvas1 = document.getElementById("image");
            var ctxImg = canvas1.getContext("2d");
            ctxImg.drawImage(img, 0, 0, img.width, img.height, 0, 0, canvas.width, canvas.height);
            ctx.beginPath();
                ctx.moveTo(0,0)
                ctx.lineTo(100,100)
                ctx.lineTo(200, 50);
                ctx.lineTo(310, 100);
                ctx.lineWidth = 10;
                ctx.stroke()
                ctx.closePath();
              //  ctx.clip();
            ctx.globalCompositeOperation = 'source-in';
                ctx.drawImage(img, 0, 0, img.width, img.height, 0, 0, canvas.width, canvas.height);
                ctx.restore();
            //animate();
        }
        img.src = "http://lh3.ggpht.com/_Z-i7eF_ACGI/TRxpFywLCxI/AAAAAAAAAD8/ACsxiuO_C1g/house%20vector.png";
    });

      </script> 
   </head> 
   <body> 
      <p>Image clipped by moving circle</p> 
      <canvas id="canvas" width="300" height="200"></canvas> 
      <br> 
      <p>Unclipped image</p> 
      <canvas id="image" width="300" height="200"></canvas>  
   </body>
</html>

Related Tutorials