图像作为绘制形状的"背景"

Cha*_*lie 17 html5 canvas

是否可以使用图像而不是颜色在HTML5画布上"填充"形状?

我画了一堆形状(各种角落的正方形以45度角切开).我希望能够用图像"填充"这些形状,而不是颜色.目前我有一条线说:

context.fillStyle = '#123456' // example fill color
Run Code Online (Sandbox Code Playgroud)

我正在寻找的是:

context.fillStyle = 'url(http://www.myimagereference.com/image.png)';
Run Code Online (Sandbox Code Playgroud)

我知道我不能以这种方式使用fillStyle - 但还有另一种方法可以实现这种方式吗?

小智 16

您可能想看看 下面的createPattern
是一个简单的代码,它演示了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);
};
Run Code Online (Sandbox Code Playgroud)

试试一个例子

  • 请注意,(据我所知)“ createPattern”不允许您按比例或其他方式缩放图像。根据使用情况,这可能很好。如果需要拉伸,则可以使用我的答案,也可以将拉伸后的图像绘制到屏幕外的画布上,然后使用该画布创建图案。 (2认同)

Phr*_*ogz 12

您可以通过定义与您的形状相同的剪裁区域然后使用drawImage()绘制到此区域来完成此操作; 然后在这之上划线(仅)你的路径.

我在我的网站上为您创建了这种技术的示例:http:
//phrogz.net/tmp/canvas_image_as_background_to_shape.html

这是相关的代码; 它按比例缩放图像以填充您指定的宽度:

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
}
Run Code Online (Sandbox Code Playgroud)

如果您想要平铺,不对称拉伸,低不透明度着色等,您可以自行修改.以下是您可以使用它的方法:

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
}
Run Code Online (Sandbox Code Playgroud)

请注意,在创建要传递给函数的图像时,必须在设置以下内容之前设置onload处理程序src:

var img = new Image;
img.onload = function(){
  // Now you can pass the `img` object to various functions
};
img.src = "...";
Run Code Online (Sandbox Code Playgroud)