如何在画布贝塞尔曲线内使图像图案重塑

时间:2018-10-09 03:40:45

标签: javascript html canvas

我正在尝试将上传的图片包裹在此咖啡杯套上。我已经看过类似的堆栈溢出问题,但是我花了数周的时间试图了解它们在哪里计算贝塞尔曲线控制点,以及如何同时在垂直和水平方向上更改它们(我想我无法使用{{ 3}}。因此,我改用了bezierCurveTo()方法来设置我想要的图像的参数,因为这样可以更轻松地理解两者的用法,并尝试使图像成为填充轮廓的图案。我在本地运行代码时得到的是: this one 如您所见,轮廓的底部有一小幅我想要的照片,但它应该覆盖整个区域。如何使图像图案充满整个黄色轮廓区域?

这是我的代码:

var cdEdit = document.getElementById("cdEdit");
var faceCanvas = document.getElementById("face");
var ctx = cdEdit.getContext("2d");
var faceCtx = face.getContext("2d");

var cup = new Image();
cup.crossOrigin = 'anonymous';
cup.onload = draw;
cup.src = 'https://image.ibb.co/d5psR9/sleeve_Clean.png';

var cupTop = 147;
var cupBottom = 399;
var dxx = 19;
var dyy = -29;
var l = {
  x0: 115,
  y0: cupTop,
  x1: 138,
  y1: cupBottom
};
var r = {
  x0: 384,
  y0: cupTop,
  x1: 361,
  y1: cupBottom
};
var t = {
  x0: l.x0,
  y0: l.y0,
  x1: l.x0 + dxx,
  y1: r.y0 + dyy,
  x2: r.x0 - dxx,
  y2: r.y0 + dyy,
  x3: r.x0,
  y3: r.y0
};
var b = {
  x0: l.x1,
  y0: l.y1,
  x1: l.x1 + dxx,
  y1: r.y1 - 5,
  x2: r.x1 - dxx,
  y2: r.y1 - 5,
  x3: r.x1,
  y3: r.y1
};

function d() {
  ctx.beginPath();
  ctx.moveTo(l.x0, l.y0);
  ctx.bezierCurveTo(95, 320, 124, 350, l.x1, l.y1);
  ctx.moveTo(r.x0, r.y0);
  ctx.bezierCurveTo(403, 320, 381, 350, r.x1, r.y1);
  ctx.lineWidth = 1;
  ctx.stroke()

  ctx.beginPath();
  ctx.moveTo(t.x0, t.y0);
  ctx.bezierCurveTo(t.x1, t.y1, t.x2, t.y2, t.x3, t.y3);
  ctx.stroke();

  ctx.beginPath();
  ctx.moveTo(b.x0, b.y0);
  ctx.bezierCurveTo(b.x1, b.y1, b.x2, b.y2, b.x3, b.y3);
  ctx.stroke();

  var imgTest = new Image();
  imgTest.crossOrigin = 'anonymous';
  imgTest.src = "https://preview.ibb.co/eicOYp/sample_Wrap.jpg";
  imgTest.onload = function() {
    //ctx.drawImage(imgTest,0,0);
    var imgpat = ctx.createPattern(imgTest, "no-repeat");
    ctx.fillStyle = imgpat;
    ctx.fill();
  }
}

function draw() {
  ctx.strokeStyle = 'gold';
  ctx.clearRect(0, 0, cdEdit.width, cdEdit.height);
  ctx.drawImage(cup, 0, 0);
  d();
}
<canvas id="cdEdit" width="700px;" height="500px;">
		<canvas id="face" hidden>
		</canvas>
</canvas>

0 个答案:

没有答案