0

I need to have a program that allows the user to clip an image with a rectangle:

https://jsfiddle.net/w3qfLr10/58/

I expected that when I clicked on different locations on the canvas, the program will clip the background image at that location. However, as you can see from the link, each time the mouse is clicked, the screen does not get refreshed. I expected the background is only clipped by one rectangle at the latest mouse location; instead, it seems like the background is clipped by all the mouse clicks.Thanks

Here is my code:

<html>
  <head>
      <style>
          body {
              margin: 0px;
              padding: 0px;
         }
    </style>
  </head>
  <body>

    <canvas id='myCanvas' width="480" height="320"> </canvas>

    <script >
        var canvas = document.getElementById('myCanvas');
        var context = canvas.getContext('2d');
        var imageObj = new Image();
        var rectX = 75;
        var rectY = 60;

        function draw() {
          context.clearRect(0,0, canvas.width, canvas.height);
          context.beginPath();
          context.rect(rectX, rectY, 250, 180);
          context.clip();
            context.drawImage(imageObj, 69, 50);
        };

        imageObj.onload = function() {
            draw();
            canvas.onmouseup = function(e) {
                rectX = e.x;
                rectY = e.y;
                draw();
            };
        };
        imageObj.src = 'http://www.html5canvastutorials.com/demos/assets/darth-vader.jpg';



        </script>

    </body>
</html> 
long
  • 1
  • 1
  • 5

1 Answers1

0

I figured out what was wrong. To make the program behaves the way I intended it to behave, I just need to add context.save() before the path and context.restore() after the drawing. So, the new code would look like this:

....
      context.clearRect(0,0, canvas.width, canvas.height);
      context.save();  //new code
      context.beginPath();
      context.rect(rectX, rectY, 250, 180);
      context.clip();
      context.drawImage(imageObj, 69, 50);
      context.restore();//new code
long
  • 1
  • 1
  • 5