Canvas How to - Create pattern from another canvas








Question

We would like to know how to create pattern from another canvas.

Answer


<!--from  w  w  w  . ja va 2 s .  c  om-->
<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'>//<![CDATA[ 
window.onload=function(){
    var mainCanvas = document.getElementById('mainCanvas');
    var textureCanvas = document.getElementById('textureCanvas');
    var mainContext = mainCanvas.getContext('2d');
    var textureContext = textureCanvas.getContext('2d');
    textureContext.fillStyle = 'grey';
    textureContext.fillRect(0, 0, 1, 1);
    textureContext.fillStyle = 'lightgrey';
    textureContext.fillRect(1, 0, 1, 1);
    textureContext.fillStyle = 'grey';
    textureContext.fillRect(2, 0, 1, 1);
    var pattern = mainContext.createPattern(textureCanvas, 'repeat');
    mainContext.fillStyle = pattern;
    mainContext.fillRect(0, 0, 198, 99);
}//]]>  
</script>
</head>
<body>
  <canvas id="mainCanvas" width="200" height="200"/>
  <canvas id="textureCanvas" width="3" height="1"></canvas>
</body>
</html>

The code above is rendered as follows: