HTML5 canvas clip() doesn't work in Chrome whe

2019-02-15 18:36发布

问题:

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:

   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(); // !!! Image below is invisible in Chrome when clip() is enabled
      
      var objectImage = document.getElementById("test");
      ctx.drawImage(objectImage, 0, 0);
   }
<canvas id="mainCanvas" width="320" height="240" style = "border:1px solid #d3d3d3;"></canvas>
<img id="test" width="0" height="0" src="https://dl.dropboxusercontent.com/u/4111969/test.png">

The code works fine in Firefox:

But in Chrome the image inside the rectangle is empty:

Translate and scale transformations seem to work fine, but not the rotate. Am I doing something wrong? If it's a bug in Chrome, is there a good workaround?

Edit:

My system is: Chrome "Version 49.0.2623.87 m", Windows 7 Home Premium SP1, ASUS R7 250X graphics card. I can reproduce the problem every time.

I found that the problem goes away if I turn off hardware acceleration in the browser settings. As I understand this means there's probably a problem with my graphics card driver.

Is there a way for my webpage to force the software rendering in Chrome?

回答1:

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>



回答2:

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.