Skip to content
html
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    html, 
    body {
      width: 100vw;
      height: 100vh;
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
    }
  </style>
</head>
<body>
  <canvas id="canvas"></canvas>
  <img src="./imgs/create-pattern.png" alt="">

  <script>
    const canvas = document.querySelector('#canvas')
    const context = canvas.getContext('2d')
    const img = new Image()

    canvas.width = 400
    canvas.height = 400
    canvas.style.background = '#ddd'

    img.src = "./imgs/floral.png"
    img.onload = (e => {
      /**
       * 使用指定的图像创建模式的方法。 它通过repetition参数在指定的方向上重复元图像。此方法返回一个CanvasPattern对象。
       *
       * @param {CanvasImageSource} image 作为重复图像源的 CanvasImageSource 对象。
       *  可以是下列之一:HTMLImageElement (<img>) | HTMLVideoElement (<video>) | 
       *  HTMLCanvasElement (<canvas>) | CanvasRenderingContext2D | 
       *  ImageBitmap | ImageData | Blob
       * @param {string} repetition 指定如何重复图像。允许的值有:repeat || 
       *  repeat-x || repeat-y || no-repeat。如果为 '' 或 null,repetition
       *  将被当作"repeat"。
       * @return {CanvasPattern} 描述模式的不透明对象
       */
      const pattern = context.createPattern(e.target, 'repeat')

      context.fillStyle = pattern
      context.fillRect(0, 0, canvas.width, canvas.height)
    })
  </script>
</body>
</html>