Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML5 canvas smearing image patterns when translating

Weird issue when using 'no-repeat', 'repeat-x' or 'repeat-y' when creating a pattern using an image. Consider the following:

<!DOCTYPE HTML>
<html>
  <head>
    <style>
      body {
        margin: 0px;
        padding: 0px;
      }
    </style>
  </head>
  <body>
    <canvas id="myCanvas" width="578" height="200"></canvas>
    <script>
      var canvas = document.getElementById('myCanvas');
      var context = canvas.getContext('2d');

      var imageObj = new Image();
      imageObj.onload = function() {        

        context.rect(0, 0, canvas.width, canvas.height);
        context.translate(50,50);
        
        var pattern = context.createPattern(imageObj, 'no-repeat');
        context.fillStyle = pattern;
        context.fill();
      };
      imageObj.src = 'http://www.html5canvastutorials.com/demos/assets/wood-pattern.png';
    </script>
  </body>
</html>  

I'm translating the image pattern within the shape (in this case it's a rectangle, but it occurs for any shape). On Chrome 35.0.1916.114 m, it causes a 'smearing' of the image. Is there a way to avoid the smear effect or am I doing something insanely wrong.

Fiddle

screen shot:
Example Screen Shot

like image 882
ni3po42 Avatar asked Nov 01 '22 22:11

ni3po42


1 Answers

context.translate applies to the starting point to draw on the canvas. Instead you want to fill a certain portion of the rectangle.

imageObj.onload = function() {
  var width = 600;
  var height = 400;
  var patOffsetX = 50;
  var patOffsetY = 50;

  context.rect(0, 0, width, height);

  var pattern = context.createPattern(imageObj, 'repeat');
  context.fillStyle = pattern;
  context.fillRect(patOffsetX, patOffsetY, width - patOffsetX, height - patOffsetY);
  context.stroke(); //added to help see the rect
};

I also updated the size of the canvas to see it working.

<canvas id="myCanvas" width="800" height="400"></canvas>

Fiddle

like image 65
Ballbin Avatar answered Nov 12 '22 15:11

Ballbin