html5 – 图像作为绘制形状的“背景”

前端之家收集整理的这篇文章主要介绍了html5 – 图像作为绘制形状的“背景”前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
是否可以使用图像而不是颜色“填充”HTML5画布上的形状?

我画了一堆形状(四角形以45度角切片)。我想能够用图像“填充”这些形状,而不是颜色。现在我有一句话说:

  1. context.fillStyle = '#123456' // example fill color

我正在寻找的是像:

  1. context.fillStyle = 'url(http://www.myimagereference.com/image.png)';

我知道我不能以这种方式使用fillStyle – 但是有另一种方式来实现这种事情吗?

解决方法

您可以通过定义与您的形状相同的 clipping region,然后使用drawImage()绘制到此区域来执行此操作;然后中风(只)你的路径在此之上。

我在我的网站上为你创建了一个这样的技术的例子:
http://phrogz.net/tmp/canvas_image_as_background_to_shape.html

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

  1. function clippedBackgroundImage( ctx,img,w,h ){
  2. ctx.save(); // Save the context before clipping
  3. ctx.clip(); // Clip to whatever path is on the context
  4.  
  5. var imgHeight = w / img.width * img.height;
  6. if (imgHeight < h){
  7. ctx.fillStyle = '#000';
  8. ctx.fill();
  9. }
  10. ctx.drawImage(img,imgHeight);
  11.  
  12. ctx.restore(); // Get rid of the clipping region
  13. }

如果你想要平铺,不对称拉伸,低透明度着色等等,你可以修改它。这是你可以如何使用它:

  1. function slashedRectWithBG( ctx,x,y,h,slash,img ){
  2. ctx.save(); // Save the context before we muck up its properties
  3. ctx.translate(x,y);
  4. ctx.beginPath();
  5. ctx.moveTo( slash,0 ); ////////////
  6. ctx.lineTo( w,0 ); // //
  7. ctx.lineTo( w,h-slash ); // //
  8. ctx.lineTo( w-slash,h ); // //
  9. ctx.lineTo( 0,h ); // //
  10. ctx.lineTo( 0,slash ); ////////////
  11. ctx.closePath();
  12. clippedBackgroundImage( ctx,h );
  13. ctx.stroke(); // Now draw our path
  14. ctx.restore(); // Put the canvas back how it was before we started
  15. }

请注意,当您创建图像传递给该功能时,您必须要set its onload handler before setting the src

  1. var img = new Image;
  2. img.onload = function(){
  3. // Now you can pass the `img` object to varIoUs functions
  4. };
  5. img.src = "...";

猜你在找的HTML5相关文章