[英]Canvas: Fill triangle with inner stroke
我有两个三角形:
斯托克用夹子计算
ctx.beginPath();
ctx.moveTo(a.x, a.y);
ctx.lineTo(b.x, b.y);
ctx.lineTo(c.x, c.y);
ctx.lineTo(a.x, a.y);
ctx.closePath();
ctx.lineWidth = obj.data.borderWidth * 2;
ctx.strokeStyle = obj.data.borderColor;
ctx.save();
ctx.clip();
ctx.stroke();
ctx.restore();
我想在笔划内创建新三角形并填充它。 如何获得新三角形的坐标?
我如何解决这个问题:
定义用于查找点之间的距离、查找矢量角度、按角度和距离计算新点的函数:
function vectorAngle(a, b) {
return (Math.atan2(b.y - a.y, b.x - a.x) * 180) / Math.PI;
}
function newPointByAngle(point, length, angle) {
const x = point.x + Math.cos((Math.PI * angle) / 180) * length;
const y = point.y + Math.sin((Math.PI * angle) / 180) * length;
return { x, y };
}
function vectorDistance(a, b) {
return Math.hypot(b.x - a.x, b.y - a.y);
}
和用于在循环中查找所需点的功能
function findInnerTriangle(a, b, c) {
const ca_angle = vectorAngle(c, a);
const cb_angle = vectorAngle(c, b);
const left_point = newPointByAngle(c, vectorDistance(c, a), ca_angle);
const left_point_with_border = newPointByAngle(left_point, border, ca_angle - 90);
const right_point = newPointByAngle(c, vectorDistance(c, b), cb_angle);
const right_point_with_border = newPointByAngle(right_point, border, cb_angle + 90);
const target_point = { x: a.x, y: a.y - border };
let a_handed_point = left_point_with_border;
const left_angle = ca_angle + 180;
for (let i = 0; a_handed_point.y >= target_point.y; i++) {
a_handed_point = newPointByAngle(left_point_with_border, i, left_angle);
}
let b_handed_point = left_point_with_border;
const right_angle = cb_angle + 180;
for (let i = 0; b_handed_point.y >= target_point.y; i++) {
b_handed_point = newPointByAngle(right_point_with_border, i, right_angle);
}
let c_handed_point = left_point_with_border;
for (let i = 0; vectorAngle(c_handed_point, b_handed_point) <= cb_angle; i++) {
c_handed_point = newPointByAngle(left_point_with_border, i, left_angle);
}
return { a_handed_point, b_handed_point, c_handed_point };
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.