如何使用画布创建半滴和半砖图案

时间:2016-10-17 13:35:15

标签: javascript jquery html5 canvas

我使用canvas

创建了这样的图像

enter image description here

我想使用canvas

创建这样的图像

enter image description here

这是我已经完成的代码。

<div id="canvas_div" style="z-index:15; line-height: 1">
    <img src="http://www.tiikoni.com/tis/view/?id=5eaacda" id="uploaded_image" style="display:none;">
    <canvas id="canvasBottom" width="490" height="425"></canvas>
    <canvas id="designCanvas" width="470" height="405"></canvas>
</div>

var canvas = document.getElementById('designCanvas');
var ctx = canvas.getContext('2d');
var img = document.createElement('img');
img.setAttribute('crossOrigin', 'anonymous');
img.src = window.localStorage.getItem('design_image');
var imgwidth = 0;
var imgheight = 0;
img.onload = function() { 
  imgwidth = img.width / 6.5;
  imgheight = img.height / 6.5;
  fillPattern(this, imgwidth, imgheight)
};

var canvas2 = document.getElementById("canvasBottom");
var ctx2 = canvas2.getContext("2d");

drawRulers(ctx2, 20, 25, 25);

function drawRulers(t, e, n, s) {
  i = 20;
  var o = document.getElementById("designCanvas"),
      r = displayWidth(o, i),
      a = displayHeight(o, i);
  t.fillStyle = "#efefef", t.fillRect(i, 0, r, i), t.fillRect(0, i, i, a), t.fillStyle = "#333333", t.fillRect(0, 0, i, i), t.beginPath(), t.font = "12px Lato", t.fillStyle = "#ffffff", t.textAlign = "center", t.fillText("in.", i / 2, i - 5);
  var l = !0,
      c = !0;
  t.fillStyle = "#333333";
  for (var d = 1; n >= d; d += 1) {
    var h = d * e,
        u = d + "";
    12 > n && !l || 32 > n && !l && c || n >= 32 && d % 12 == 0 ? t.fillText(u, h + i, i - 3) : t.fillText(l ? "\u0131" : "|", h + i, i - 2), l = !l, l || (c = !c)
  }
  l = !0, c = !0, t.textAlign = "right";
  for (var p = 1; s >= p; p += 1) {
    var f = p * e;
    u = p + "", 12 > s && !l || 32 > s && !l && c || s >= 32 && p % 12 == 0 ? t.fillText(u, i - 1, f + i + 2, 18) : t.fillText(l ? "-" : "\u2014", i, f + i + 1, 18), l = !l, l || (c = !c)
  }
}

function displayWidth(t, e) {
  return t.width - e
}

function displayHeight(t, e) {
  return t.height - e
}

function fillPattern(img, w, h) {
  ctx.drawImage(img, 0, 0, w, h);

  while (w < canvas.width) {
      ctx.drawImage(canvas, w, 0);
      w *= 2;
  }
  while (h < canvas.height) {
      ctx.drawImage(canvas, 0, h);
      h *= 2;
  }
}

请指导我如何使其像所需的图像一样。

任何帮助都将不胜感激。

1 个答案:

答案 0 :(得分:2)

您应该在正确的位置重复绘制图像,而不是重复画布:

<input id="code">
<button onclick="doIt()">Check it</button>

这是工作的jsfiddle:
https://jsfiddle.net/7r9ej2q1/