Image as a 'background' to a drawn Shape

后端 未结 2 2038
我寻月下人不归
我寻月下人不归 2021-02-05 11:00

Is it possible to \'fill\' a shape on an HTML5 canvas with an image instead of a color?

I\'ve drawn a bunch of shapes (squares with various corners sliced off at 45 degr

2条回答
  •  北恋
    北恋 (楼主)
    2021-02-05 11:33

    You might wanna have a look at createPattern
    below is a simple code which demonstrates the use of createPattern

    var canvas = document.getElementById("canvas");
    var ctx = canvas.getContext("2d");
    var w = canvas.width = 256;
    var h = canvas.height = 256;
    var img = new Image();
    
    img.src = "http://www.gravatar.com/avatar/e555bd971bc2f4910893cd5b785c30ff?s=128&d=identicon&r=PG";
    img.onload = function () {
        var pattern = ctx.createPattern(img, "repeat");
        ctx.fillStyle = pattern;
        ctx.fillRect(0, 0, w, h);
    };
    

    Try an Example

提交回复
热议问题