Image as a 'background' to a drawn Shape

后端 未结 2 2037
我寻月下人不归
我寻月下人不归 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 = "...";
    

提交回复
热议问题