Skip to content Skip to sidebar Skip to footer

Image As A 'background' To A Drawn Shape

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 degree angles). I'

Solution 1:

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:

functionclippedBackgroundImage( ctx, img, w, h ){
  ctx.save(); // Save the context before clipping
  ctx.clip(); // Clip to whatever path is on the contextvar 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 = newImage;
img.onload = function(){
  // Now you can pass the `img` object to various functions
};
img.src = "...";

Post a Comment for "Image As A 'background' To A Drawn Shape"