且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

HTML5 画布背景图像重复

更新时间:2022-06-23 05:07:43

使用画布' createPattern 函数

Use the canvas' createPattern function

const canvas = document.getElementById("canvas"),
      context = canvas.getContext("2d"),
      img = new Image();

img.src = 'https://www.google.nl/images/srpr/logo3w.png';

img.addEventListener('load', () => {
  const ptrn = context.createPattern(img, 'repeat'); // Create a pattern with this image, and set it to "repeat".
  context.fillStyle = ptrn;
  context.fillRect(0, 0, canvas.width, canvas.height); // context.fillRect(x, y, width, height);
})

<canvas id="canvas" width="600px" height="600px"></canvas>

(这是 2 个样本中最快的).

或者,尝试手动实施:

const canvas = document.getElementById("canvas"),
      context = canvas.getContext("2d"),
      img = new Image();

img.src = 'https://www.google.nl/images/srpr/logo3w.png';

img.addEventListener('load', () => {
  for (let w = 0; w < canvas.width; w += img.width) {
    for (let h = 0; h < canvas.height; h += img.height) {
      context.drawImage(img, w, h);
    }
  }
})

<canvas id="canvas" width="600px" height="600px"></canvas>