Ví dụ tạo pattern trong canvas Code: <!DOCTYPE html> <html> <body> <p>Ảnh sử dụng:</p> <img src="https://webvn.com/wp-content/uploads/2014/10/57.png" id="lamp" width="57" height="57"> <p>Canvas:</p> <button onclick="draw('repeat')">Lặp</button> <button onclick="draw('repeat-x')">Lặp ngang</button> <button onclick="draw('repeat-y')">Lặp dọc</button> <button onclick="draw('no-repeat')">Không lặp</button> <canvas id="myCanvas" width="300" height="150" style="border:1px solid #d3d3d3;">Trình duyệt của bạn không hỗ trợ thẻ canvas trong HTML5.</canvas> <script> function draw(direction) { var c = document.getElementById("myCanvas"); var ctx = c.getContext("2d"); ctx.clearRect(0, 0, c.width, c.height); var img = document.getElementById("lamp") var pat = ctx.createPattern(img, direction); ctx.rect(0, 0, 150, 100); ctx.fillStyle = pat; ctx.fill(); } </script> </body> </html> Kết quả: