HTML5 canvas background image repeat

后端 未结 1 1388
时光取名叫无心
时光取名叫无心 2020-12-09 10:40

I have a html5 canvas that draws a sound wave. I have set the background as an background image, however, I want this background image to repeat. Can anyone tell me how I wo

相关标签:
1条回答
  • 2020-12-09 11:07

    Use the canvas' createPattern function

    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>

    (This is the fastest of the 2 samples).

    Or, try a manual implementation:

    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 讨论(0)
提交回复
热议问题