Canvas How to - Translate an image








Question

We would like to know how to translate an image.

Answer


<!DOCTYPE html>
<!--from  www  . ja  v  a  2 s  .c  o m-->
<html>
  <head>
    <title>Manipulating images and video</title>
    <meta charset="utf-8">
    
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
    
    <script type="text/javascript">
      $(document).ready(function() {  
        var canvas = $("#myCanvas");
        var context = canvas.get(0).getContext("2d");
        
        // Translating an image
        context.translate(100, 100);
        
        var image = new Image();
        image.src = "http://www.java2s.com/style/download.png";
        $(image).load(function() {
          context.drawImage(image, 0, 0, 500, 500, 0, 0, 300, 300);
        });
        
      });
    </script>
  </head>
  
  <body>
    <canvas id="myCanvas" width="500" height="500">
      <!-- Insert fallback content here -->
    </canvas>
  </body>
</html>

The code above is rendered as follows: