HTML5 canvas 背景图片重复

标签 html canvas background background-image

我有一个绘制声波的 html5 Canvas 。我已将背景设置为背景图像,但是,我希望重复此背景图像。谁能告诉我该怎么做以及我需要在我的代码中添加什么:

var backgroundImage = new Image(); 
backgroundImage.src = 'http://www.samskirrow.com/client-kyra/images/main-bg.jpg'; 
var canvas;
var context;

function init(c) {
    canvas = document.getElementById(c);
    context = canvas.getContext("2d");
    soundManager.onready(function() {
        initSound(clientID, playlistUrl);
    });
    aniloop();
}

function aniloop() {
    requestAnimFrame(aniloop);
    drawWave();
}

function drawWave() {

    var step = 10;
    var scale = 60;

    // clear
    context.drawImage(backgroundImage, 0, 0);

    // left wave
    context.beginPath();
    context.moveTo(0, 256);
    for ( var i = 0; i < 256; i++) {
        context.lineTo(6 * i, 257 + waveLeft[i] * 80.);
    }
    context.lineWidth = 1;
    context.strokeStyle = "#000";
    context.stroke();

    // right wave
    context.beginPath();
    context.moveTo(0, 256);
    for ( var i = 0; i < 256; i++) {
        context.lineTo(6 * i, 256 + waveRight[i] * 80.);
    }
    context.lineWidth = 1;
    context.strokeStyle = "#000";
    context.stroke();
}

function updateWave(sound) {
    waveLeft = sound.waveformData.left;
}

return {
    init : init
};
})();

您可以在此处查看此代码: http://www.samskirrow.com/client-kyra

最佳答案

使用 Canvas ' createPattern功能

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>

(这是 the fastest of the 2 samples )。

或者,尝试手动实现:

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>

关于HTML5 canvas 背景图片重复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14121719/

相关文章:

html - :not里面的伪类

javascript - 单击时更改按钮的显示图像

html - CSS3 : Transform animation for pseudo element

CSS 渐变...意见?

linux - rlwrap 在后台运行时挂起作业

html - 与按下提交按钮时将信息拉入文本框相比,表单的用途是什么?

javascript - 为什么 canvas.toDataURL() 不会为图像生成与 Ruby 中相同的 base64?

python - Tkinter : Make canvas draggable

java - 如何使用javaFX Canvas绘制图像图案

windows - 修复 Windows 10 中最小化/最大化/关闭下的黑色工具提示背景