【问题标题】:Canvas resize image object and repeat pattern画布调整图像对象的大小并重复图案
【发布时间】:2015-10-26 12:11:25
【问题描述】:

我的画布是 500px x 500px。 我有一个 500px x 500px 的 png 图像:

我想将图像重新调整为... 100px x 100px,然后使用调整后的图像作为定义重复图案的一部分,然后将其用作填充样式以在整个画布上重复。这就是我的工作......

//...define canvas, ctx, width and height above

var image = new Image();
image.onload = function() {
  _self = this;
  drawBG();
}
image.src = 'img.png';

function drawBG() {
  var space = ctx.createPattern(_self, 'repeat');
  ctx.fillStyle = space;
  ctx.fillRect(0, 0, width, height);
}

现在,如果我想浪费自己的时间,这一切都很好。看,空间图像与画布大小相同。我的问题是......你如何首先调整原始图像(在 javascript 中)的大小,然后再用它创建一个图案?

附:如何在堆栈溢出时重新调整图像大小?我在这里展示的这张图片对于它的目的来说太大了。

【问题讨论】:

    标签: javascript html canvas


    【解决方案1】:

    您可以使用drawImage(img, x, y, resizedWidth, resizedHeight) 在第二个屏幕外画布上绘制图像,然后将此画布用作图案。

    var ctx = canvas.getContext('2d');
    var image = new Image();
    image.onload = function() {
      // create an off-screen canvas
      var patt = document.createElement('canvas');
      // set the resized width and height
      patt.width = 50;
      patt.height = 50;
      patt.getContext('2d').drawImage(this, 0,0, patt.width, patt.height);
      // pass the resized canvas to your createPattern
      drawBG(patt);
    }
    image.src = 'http://lorempixel.com/500/500';
    
    function drawBG(patternCanvas) {
      var space = ctx.createPattern(patternCanvas, 'repeat');
      ctx.fillStyle = space;
      ctx.fillRect(0, 0, 400, 200);
    }
    <canvas id="canvas" width="500" height="250"></canvas>

    【讨论】:

      猜你喜欢
      • 2020-10-19
      • 1970-01-01
      • 2011-05-09
      • 1970-01-01
      • 2014-05-07
      • 2011-11-17
      • 2012-08-27
      • 2017-04-22
      • 1970-01-01
      相关资源
      最近更新 更多