【问题标题】:Image as a 'background' to a drawn Shape图像作为绘制形状的“背景”
【发布时间】:2011-02-10 16:52:32
【问题描述】:

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

我画了一堆形状(各种角以 45 度角切掉的正方形)。我希望能够用图像而不是颜色来“填充”这些形状。目前我有一条线说明:

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

我正在寻找的是这样的:

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

我知道我不能以这种方式使用 fillStyle - 但是还有其他方法可以实现这种事情吗?

【问题讨论】:

    标签: html canvas


    【解决方案1】:

    你可能想看看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);
    };
    

    Try an Example

    【讨论】:

    • 请注意,createPattern(据我所知)不允许您按比例或其他方式缩放图像。这可能没问题,具体取决于用例。如果您需要拉伸,您可以使用我的答案,或者将拉伸的图像绘制到屏幕外画布并使用该画布创建图案。
    【解决方案2】:

    您可以通过定义一个与您的形状相同的clipping region,然后使用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
    }
    

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

    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
    }
    

    请注意,当您创建要传递给函数的图像时,您必须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 = "...";
    

    【讨论】:

    • 非常感谢您花时间回答并提供演示。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-10-10
    • 2016-08-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多