Image as a 'background' to a drawn Shape

后端 未结 2 2039
我寻月下人不归
我寻月下人不归 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 can do this by defining a clipping region that is the same as your shape and then using drawImage() to draw into this region; then stroke (only) your path on top of this.

    I've created an example of this technique for you on my website:
    http://phrogz.net/tmp/canvas_image_as_background_to_shape.html

    Here's the relevant code; it proportionately scales the image to fill the width you specify:

    function clippedBackgroundImage( ctx, img, w, h ){
      ctx.save(); // Save the context before clipping
      ctx.clip(); // Clip to whatever path is on the context
    
      var imgHeight = w / img.width * img.height;
      if (imgHeight < h){
        ctx.fillStyle = '#000';
        ctx.fill();
      }
      ctx.drawImage(img,0,0,w,imgHeight);
    
      ctx.restore(); // Get rid of the clipping region
    }
    

    It's up to you to modify that if you want tiling, or asymmetric stretching, low-opacity tinting, etc. Here's how you might use it:

    function slashedRectWithBG( ctx, x, y, w, h, slash, img ){
      ctx.save(); // Save the context before we muck up its properties
      ctx.translate(x,y);
      ctx.beginPath();
      ctx.moveTo( slash, 0 );       //////////// 
      ctx.lineTo( w, 0 );          //         //
      ctx.lineTo( w, h-slash );   //          //
      ctx.lineTo( w-slash,h );    //          //
      ctx.lineTo( 0, h );         //         //
      ctx.lineTo( 0, slash );     ////////////
      ctx.closePath();
      clippedBackgroundImage( ctx, img, w, h );
      ctx.stroke();  // Now draw our path
      ctx.restore(); // Put the canvas back how it was before we started
    }
    

    Note that when you create your image to pass to the function, you must set its onload handler before setting the src:

    var img = new Image;
    img.onload = function(){
      // Now you can pass the `img` object to various functions
    };
    img.src = "...";
    
    0 讨论(0)
  • 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

    0 讨论(0)
提交回复
热议问题