绘制图像轮廓的最佳实践

时间:2018-08-25 15:35:08

标签: javascript html css html5-canvas

我尝试了3种方法来制作它,但是效果并不理想。

  1. 复制并填充图像,然后进行偏移。演示是

var ctx = canvas.getContext('2d'),
    img = new Image;

img.onload = draw;
img.src = "http://i.stack.imgur.com/UFBxY.png";

function draw() {

  var dArr = [-1,-1, 0,-1, 1,-1, -1,0, 1,0, -1,1, 0,1, 1,1], // offset array
      s = 20,  // thickness scale
      i = 0,  // iterator
      x = 5,  // final position
      y = 5;
  
  // draw images at offsets from the array scaled by s
  for(; i < dArr.length; i += 2)
    ctx.drawImage(img, x + dArr[i]*s, y + dArr[i+1]*s);
  
  // fill with color
  ctx.globalCompositeOperation = "source-in";
  ctx.fillStyle = "red";
  ctx.fillRect(0,0,canvas.width, canvas.height);
  
  // draw original image in normal mode
  ctx.globalCompositeOperation = "source-over";
  ctx.drawImage(img, x, y);
}
<canvas id=canvas width=500 height=500></canvas>
。当轮廓宽度较大时,轮廓结果将是错误的。

  1. 基于Marching Squares算法检查图像的边缘。当图像形状为圆形时,轮廓带有锯齿。如果使轮廓更平滑,将不适合星形之类的尖锐形状。

  2. 复制并填充图像,然后缩放比例。当图像宽度与高度不相等时,它将不起作用。

1 个答案:

答案 0 :(得分:2)

您可以尝试使用数学方法,而无需偏移数组

var ctx = canvas.getContext('2d'),
  img = new Image;

img.onload = draw;
img.src = "http://i.stack.imgur.com/UFBxY.png";

function draw() {
  var s = 20, // thickness scale
    x = 5, // final position
    y = 5;

  for (i=0; i < 360; i++)
    ctx.drawImage(img, x + Math.sin(i) * s, y + Math.cos(i) * s);

  // fill with color
  ctx.globalCompositeOperation = "source-in";
  ctx.fillStyle = "red";
  ctx.fillRect(0, 0, canvas.width, canvas.height);

  // draw original image in normal mode
  ctx.globalCompositeOperation = "source-over";
  ctx.drawImage(img, x, y);
}
<canvas id=canvas width=500 height=500></canvas>

我的想法来自我们使用字符串绘制圆的方式:
https://www.wikihow.com/Draw-a-Perfect-Circle-Using-a-Pin

想象一下,我们只需要用一个形状代替字符串末尾的铅笔


这里是我和您的方法的视觉比较,同时我正在展示第三个缩放图像的方法,实际上没有最好的方法,这只是个人喜好问题。

您可以创建一种混合模式,如果发际线对您很重要,请缩放图像的那一部分,然后对身体的其余部分使用其他方式。

相关问题