1719886-1.html (1020B)
1 <!DOCTYPE html> 2 <html> 3 <body> 4 Pattern Canvas<br> 5 <canvas id="patternCanvas" style="border: 1px solid black" width="10" height="10"></canvas><br> 6 Main Canvas (red square should be in top-left corner)<br> 7 <canvas id="canvas" style="border: 1px solid black" width="100" height="100"></canvas> 8 <script> 9 10 // Draw a 10x10 red rectangle that will be used for the pattern. 11 const patternCanvas = document.getElementById("patternCanvas"); 12 const patternCtx = patternCanvas.getContext("2d"); 13 patternCtx.fillStyle = "red"; 14 patternCtx.fillRect(0, 0, patternCanvas.width, patternCanvas.height); 15 16 const canvas = document.getElementById("canvas"); 17 const ctx = canvas.getContext("2d"); 18 const height = 100; 19 ctx.translate(0, height); 20 21 const pattern = ctx.createPattern(patternCanvas, "no-repeat"); 22 // Reverse translation applied to the canvas. 23 pattern.setTransform((new DOMMatrix()).translate(0, -height)); 24 25 ctx.fillStyle = pattern; 26 // Fill the entire canvas with the pattern. 27 ctx.fillRect(0, -height, 100, 100); 28 29 </script> 30 31 </body> 32 </html>