首页 > 解决方案 > 为什么全画布不重复绘制 SVG 图案?

问题描述

我有这个代码:

function CrossTemplate(gridOptions, canvas) {

  const config = {color: '#000000', gridSize: 4, gridPadding: 0, strokeStyle: "#00000"};
  const bw = canvas.width;
  const bh = canvas.width;
  const p = 0;
  const cw = bw + p * 2 + 1;
  const ch = bh + p * 2 + 1;

  const context = canvas.getContext('2d');
  canvas.height = ch;
  canvas.width = cw;

  if (!context) throw Error('Canvas context error');

  for (var x = 0; x <= bw; x += config.gridSize) {
    context.moveTo(0.5 + x + p, p);
    context.lineTo(0.5 + x + p, bh + p);
  }

  for (var x = 1; x <= bh; x += config.gridSize) {
    context.moveTo(p, 0.5 + x + p);
    context.lineTo(bw + p, 0.5 + x + p);
  }

  context.strokeStyle = config.strokeStyle;
  context.stroke();

  return canvas;
}

https://jsfiddle.net/k2mg8dxs/12/

我想知道,为什么我没有看到图案画布,我在哪里做错了?

我使用父上下文:

const context2 = canvas2.getContext('2d');
context2.fillStyle = context.createPattern(canvas, 'repeat');

标签: javascriptcanvashtml5-canvas

解决方案


我将模式画布的创建移动到您定义的函数中,然后最后返回画布。我认为它使发生的事情更加透明。我很难阅读您的代码,但这似乎可以工作。

然后你也错过了fillRect()到底。

function CrossTemplate(gridOptions) {

  let canvas = document.createElement('canvas');

  canvas.width = 512;
  canvas.height = 512;

  const config = {
    color: '#000000',
    gridSize: 4,
    gridPadding: 0,
    strokeStyle: "#00000"
  };
  const bw = canvas.width;
  const bh = canvas.width;
  const p = 0;
  const cw = bw + p * 2 + 1;
  const ch = bh + p * 2 + 1;

  const context = canvas.getContext('2d');
  canvas.height = ch;
  canvas.width = cw;

  if (!context) throw Error('Canvas context error');

  for (var x = 0; x <= bw; x += config.gridSize) {
    context.moveTo(0.5 + x + p, p);
    context.lineTo(0.5 + x + p, bh + p);
  }

  for (var x = 1; x <= bh; x += config.gridSize) {
    context.moveTo(p, 0.5 + x + p);
    context.lineTo(bw + p, 0.5 + x + p);
  }

  context.strokeStyle = config.strokeStyle;
  context.stroke();

  return canvas;
}

const canvas2 = document.getElementById('canvas2');
canvas2.width = 1024;
canvas2.height = 1024;

let canvas = CrossTemplate({
  lineWidth: 1,
  b: 24,
  k: -1,
  strokeStyle: '#215cff',
  lineCap: 'square'
});

const context = canvas.getContext('2d');
const context2 = canvas2.getContext('2d');
context2.fillStyle = context.createPattern(canvas, 'repeat');
context2.fillRect(0, 0, canvas2.width, canvas2.height);
#canvas {
  width: 512px;
  height: 512px;
}
<canvas id="canvas2"></canvas>


推荐阅读