2013-01-02 25 views
13

Tôi có canvas html5 vẽ một wave âm thanh. Tuy nhiên, tôi đã đặt nền làm hình nền, tôi muốn hình nền này lặp lại. bất cứ ai có thể cho tôi biết làm thế nào tôi sẽ làm điều này và những gì tôi cần phải thêm vào mã của tôi:Hình nền HTML5 canvas lặp lại

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 
}; 
})(); 

Bạn có thể thấy mã này trong hành động ở đây: http://www.samskirrow.com/client-kyra

+0

bạn không thể sử dụng CSS để lặp lại nền? –

+0

@MuhammadShoaib: Không, không phải hình ảnh được vẽ lên khung vẽ. – Cerbrus

Trả lời

48

Sử dụng vải createPattern chức năng

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

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

 
img.onload = function(){ 
 
    // create pattern 
 
    var 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>

(Đây là the fastest of the 2 samples) .

Hoặc, hãy thử một việc thực hiện thủ công:

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

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

 
img.onload = function(){ 
 
    for (var w = 0; w < canvas.width; w += img.width) { 
 
     for (var h = 0; h < canvas.height; h += img.height) { 
 
      context.drawImage(img, w, h); 
 
     } 
 
    } 
 
}
<canvas id="canvas" width="600px" height="600px"></canvas>

+0

Ví dụ đầu tiên hoạt động hoàn hảo, cảm ơn –