首页 > 解决方案 > 无法使用重复模式在画布上重复图像

问题描述

我正在尝试使用我自己创建的图形在画布上创建一个简单的重复图像。不幸的是 createPattern(img, repeat) 导致只有一个版本的图像被重复。我尝试将其保存为图像,然后使用 img.src 加载该图像,我还尝试创建第二个画布并尝试使用第一个画布作为模式的基础在该画布上绘制,但两者都产生相同结果 - 只是图像的一个版本。我在这里想念什么?

这是我的代码的两个版本:

使用两个画布:

function draw() {

  var canvas1 = document.getElementById('drawcanvas')
  var ctx = canvas1.getContext('2d');
  var canvas2 = document.getElementById('canvas');
  var ctx2 = canvas2.getContext('2d');


  ctx.fillStyle = '#f5f2d0';
  ctx.fillRect(0, 0, 205, 255);
  ctx.fillStyle = '#FFF';
  ctx.fillRect(0, 0, 200, 250);
  ctx.fillStyle = '#77d499';
  ctx.fillRect(5, 5, 195, 245);
  var img = new Image();
  img.addEventListener('load', function() {
    ctx.drawImage(img, 48.75, 20, 100, 200)
  }, false)
  img.src = 'Images/wine-icon-15966.png';

  var pattern = ctx2.createPattern(canvas, 'repeat');
  ctx2.fillStyle = pattern;
  ctx.fillRect(0, 0, 2480, 3508);
}

使用单独的图像:

function draw() {

  var ctx = document.getElementById('canvas').getContext('2d');

  ctx.fillStyle = '#f5f2d0';
  ctx.fillRect(0, 0, 2480, 3508);


  ctx.fillStyle = '#FFF';
  ctx.fillRect(0, 0, 200, 250);
  ctx.fillStyle = '#77d499';
  ctx.fillRect(5, 5, 195, 245);
  var img = new Image();
  img.addEventListener('load', function() {
    ctx.drawImage(img, 48.75, 20, 100, 200)
  }, false)
  img.src = 'Images/wine-icon-15966.png';

}

谢谢你的帮助!

标签: canvashtml5-canvas

解决方案


我做了一些调整,并使用从画布绘制选项使其工作。如建议的那样,我将逻辑移到了 load 语句中。我还在 createPattern 中提到了画布,它是第二个画布的 id,而不是我给第一个画布 (drawcanvas) 的 id,这意味着我本质上是在空白画布上绘制一个空白画布。这是我更新的代码。

function draw() {

  var canvas1 = document.getElementById('drawcanvas')
  var ctx = canvas1.getContext('2d');
  var canvas2 = document.getElementById('canvas');
  var ctx2 = canvas2.getContext('2d');


  ctx.fillStyle = '#f5f2d0';
  ctx.fillRect(0, 0, 205, 255);
  ctx.fillStyle = '#FFF';
  ctx.fillRect(0, 0, 200, 250);
  ctx.fillStyle = '#77d499';
  ctx.fillRect(5, 5, 195, 245);
  var img = new Image();
  img.src = 'Images/wine-icon-15966.png';
    img.addEventListener('load', function() {
    ctx.drawImage(img, 48.75, 20, 100, 200);
    var pattern = ctx2.createPattern(drawcanvas, 'repeat');
    ctx2.fillStyle = pattern;
    ctx2.fillRect(0, 0, canvas.width, canvas.height);
    ctx2.fill();

  }, false);

  ctx2.fillStyle = '#f5f2d0';
  ctx2.fillRect(0, 0, canvas.width, canvas.height);
}

推荐阅读