gpt4 book ai didi

javascript - 绘制图像轮廓的最佳实践

转载 作者:行者123 更新时间:2023-11-30 14:25:26 24 4
gpt4 key购买 nike

我尝试了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. 复制并填充图像,然后缩放它。当图像宽度与高度不相等时,它不起作用。

最佳答案

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

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>

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

想象一下,绳子末端没有铅笔,我们只有一个形状


这是我的方法和你的方法的视觉比较,我还展示了第三种缩放图像的方法,确实没有最好的方法,这只是个人喜好的问题。

你可以创建一个混合模式,如果发际线对你很重要,让图像的那部分缩放它,然后对 body 的其余部分使用不同的方式。

关于javascript - 绘制图像轮廓的最佳实践,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52018746/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com