HTML 5 Canvas图像叠加可重复

时间:2017-07-23 04:28:43

标签: javascript jquery html5 canvas

我正在尝试拍摄一个图案并将其应用于png图像,但仅覆盖与此图像类似的图像的非透明部分。

module dir in working directory

$(function() {
var canvas = document.createElement('canvas');
canvas.width = 250;
canvas.height = 250;

var canvas_context = canvas.getContext("2d");

var img = new Image();
img.onload = function(){
    var msk = new Image();
    msk.onload = function(){
        canvas_context.drawImage(img, 0, 0);
        canvas_context.globalCompositeOperation = "destination-in";
        canvas_context.drawImage(msk, 0, 0);
        canvas_context.globalCompositeOperation = "source-over";
    };

    msk.src = 'http://i.stack.imgur.com/QtQrZ.png';
}
img.src = 'http://i.stack.imgur.com/MDGFY.jpg';

document.body.appendChild(canvas);

});

上面的示例非常接近我想要的但我需要能够使用较小的纹理图像并在无图案图像上重复它。我不熟悉如何正确使用画布,但试图了解它的更多信息。

提前致谢!

1 个答案:

答案 0 :(得分:0)

别介意我弄清楚了。

var canvas = document.createElement('canvas');
canvas.width = 250;
canvas.height = 250;

var canvas_context = canvas.getContext("2d");

var img = new Image();
img.onload = function(){
    var msk = new Image();
    msk.onload = function(){

        var ptrn = canvas_context.createPattern(img, 'repeat');
        canvas_context.fillStyle = ptrn;
        canvas_context.fillRect(0, 0, canvas.width, canvas.height);

        canvas_context.drawImage(img, 0, 0);
        canvas_context.globalCompositeOperation = "destination-in";
        canvas_context.drawImage(msk, 0, 0);
        canvas_context.globalCompositeOperation = "source-over";


    };

    msk.src = $('#base_url').data('base')+'assets/themes/img/download.png';
}

img.src = $('#base_url').data('base')+'assets/uploads/thumbs/1381413411Purple-Night-Owls-thumb.jpg';


$('#itemPreview').html(canvas);