HTML5 canvas clip() doesn't work in Chrome when rotation is applied

后端 未结 2 980
别那么骄傲
别那么骄傲 2021-01-07 04:17

I\'m trying to use a clip region on a canvas and it stops working as soon as the coordinate system is rotated by any non zero value:

相关标签:
2条回答
  • 2021-01-07 04:30

    In Chrome, drawImage() is done before Image loaded, you have to check like this:

    <!DOCTYPE HTML>
    <html>
    <script>
          window.onload = function() {
          var canvas = document.getElementById("mainCanvas");
          var ctx = canvas.getContext("2d");
          ctx.rotate(Math.PI / 8); // !!! Clipping doesn't work with any non zero value
          ctx.beginPath();
          ctx.rect(0, 0, canvas.width, canvas.height);
          ctx.stroke();
          ctx.clip(); 
          
          //Make sure the Image is loaded
          var objectImage= new Image();
          objectImage.src="https://dl.dropboxusercontent.com/u/4111969/test.png"
          objectImage.onload =function()
          {
               ctx.drawImage(objectImage, 0, 0);
          }
       }
    </script>
    <body>
        <img id="test" width="0" height="0" src="https://dl.dropboxusercontent.com/u/4111969/test.png">
        <canvas id="mainCanvas" width="320" height="240" style = "border:1px solid #d3d3d3; margin:0; padding:0"></canvas>
    </body>
    </html>

    0 讨论(0)
  • 2021-01-07 04:30

    The problem seems to be related to the browser hardware acceleration. Everything works fine as soon as I turn it off.

    However, I don't know if it's possible for my web page to disable hardware acceleration.

    0 讨论(0)
提交回复
热议问题