# 德卡斯特里奥构造

连接四个控制点，按同一比例分割相邻线段。对新得到的点再做两轮相同的计算，最后一个点就落在三次贝塞尔曲线上。

## 试一试

交替点按 t = 0.20 和 t = 0.80，依次观察三个方点、两个菱形点和曲线上的红点。

## 交互细节

t 的范围为 0 到 1，步长为 0.01。取两端值时，结果点分别与起点和终点重合。启用减弱动态效果后，预设值立即生效。

## 各平台的操作方式

- iOS · 滑动以调整比例，再用手指拖动 P₁ 或 P₂ 的圆形控制点改变曲线。
- Android · 滑动以调整比例，再用手指拖动 P₁ 或 P₂ 的圆形控制点改变曲线。
- PC · 在滑块上按左右方向键调整比例。用 Tab 选中 P₁ 或 P₂，再用方向键移动控制点。

## 适用场景

用于讲解钢笔工具的控制点如何改变曲线，也可用于演示图形学中的线性插值。

## 实现要求

> 绘制一条三次贝塞尔曲线，固定两端并允许移动中间两个控制点。使用相同的 t 反复对相邻点进行插值，在曲线上展示三点、两点和一点的三轮结果。

## 来源与致谢

[Michigan Technological University · De Casteljau’s algorithm](<https://pages.mtu.edu/~shene/COURSES/cs3621/NOTES/spline/Bezier/de-casteljau.html>)

## 独立 HTML 示例

将以下代码保存为 HTML 文件，用浏览器打开即可离线体验。

```html
<!doctype html>
<html lang="zh-Hans" data-motion-locales="inline"><head><script>if(new URLSearchParams(location.search).get('reduce')==='1')document.documentElement.classList.add('motion-reduced');</script><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>곡선 제도실 · MotionLab</title>
<style>
*{box-sizing:border-box}:root{color-scheme:light;font:15px/1.4 system-ui,sans-serif;color:#213a38;background:#eaece2}body{margin:0;min-height:100svh;display:grid;align-content:center;padding:clamp(10px,2.6vw,24px)}main{width:min(100%,680px);margin:auto}header{display:flex;align-items:end;justify-content:space-between;flex-wrap:wrap;gap:4px 12px;margin-bottom:9px}h1{font:700 clamp(21px,4vw,32px)/1.1 Georgia,serif;letter-spacing:-.025em;margin:0}header small{font-weight:650;color:#475a50}
.plate{background:#fcfaec;border:1px solid #4c635a;border-radius:5px;overflow:hidden}svg{width:100%;height:auto;display:block;touch-action:none;user-select:none}svg text{font:700 10px system-ui,sans-serif;fill:#2e413b;paint-order:stroke;stroke:#fcfaec;stroke-width:3px;pointer-events:none}g.handle{cursor:grab}g.handle:focus{outline:none}g.handle:focus-visible .grip{stroke:#a33432;stroke-width:3}.legend{display:flex;align-items:center;gap:8px 18px;flex-wrap:wrap;padding:7px 10px;background:#233f3c;color:#fffbea;font:650 12px/1.35 system-ui,sans-serif}.legend span{display:inline-flex;align-items:center;gap:5px}.legend i{width:9px;height:9px;display:inline-block}.q{background:#edb252}.r{background:#91d5c1;transform:rotate(45deg)}.p{border-radius:50%;background:#fa9181}
.controls{margin-top:10px;display:flex;align-items:center;flex-wrap:wrap;gap:7px}.controls label{font:650 14px Georgia,serif;display:flex;align-items:center;gap:5px}.controls output{font:650 13px system-ui,sans-serif;font-variant-numeric:tabular-nums;min-width:3ch}.controls input{accent-color:#336b60;flex:1 1 90px;min-width:65px}button{min-height:38px;border:1px solid #7b8e81;border-radius:5px;color:#21453e;background:#fbfae9;padding:6px 12px;font:650 13px system-ui,sans-serif;cursor:pointer}button:focus-visible,input:focus-visible{outline:3px solid #45726b;outline-offset:2px}.hint{font-size:13px;color:#41554c;margin:7px 0 0}
@media(min-width:600px) and (max-height:560px){body{padding:8px 16px}main{width:min(100%,640px)}}
</style></head><body><main>
<header><h1 data-t="title"></h1><small data-t="tech"></small></header>
<div class="plate"><svg id="board" viewBox="0 0 480 220" role="group" aria-labelledby="boardTitle" aria-describedby="hint"><title id="boardTitle" data-t="board"></title>
<defs><pattern id="paper" width="12" height="12" patternUnits="userSpaceOnUse"><path d="M12 0H0V12" fill="none" stroke="#a5b6a9" stroke-width=".48"/></pattern></defs>
<rect width="480" height="220" fill="url(#paper)"/><path d="M7 19V7h12m442 0h12v12M7 201v12h12m442 0h12v-12" fill="none" stroke="#87978a" stroke-width="1.3"/>
<polyline id="polygon" fill="none" stroke="#7c8d82" stroke-width="1.35" stroke-dasharray="4 3"/><path id="curve" fill="none" stroke="#4a5650" stroke-width="2.4"/>
<polyline id="qLine" fill="none" stroke="#b97a25" stroke-width="2"/><polyline id="rLine" fill="none" stroke="#3b8473" stroke-width="2.6"/>
<g id="roots"></g><g id="qPoints" pointer-events="none"></g><g id="rPoints" pointer-events="none"></g><g id="result" pointer-events="none"><circle r="8.8" fill="#fcfaec" stroke="#833e36" stroke-width="1.2"/><circle r="5" fill="#a9473c"/></g>
</svg><div class="legend"><span><i class="q"></i><b data-t="one"></b></span><span><i class="r"></i><b data-t="two"></b></span><span><i class="p"></i><b data-t="last"></b></span></div></div>
<div class="controls"><label for="ratio">t <output id="value" for="ratio"></output></label><input id="ratio" type="range" min="0" max="100" value="34" step="1"><button id="early">t = 0.20</button><button id="late">t = 0.80</button></div>
<p id="hint" class="hint" data-t="hint"></p></main>
<script>
const copy={
 ko:{title:'곡선 제도실',tech:'드 카스텔조 작도',board:'두 손잡이가 있는 삼차 베지에 곡선',one:'첫 보간점 3개',two:'둘째 보간점 2개',last:'곡선 위의 점',handle:'제어점',ratio:'보간 비율',hint:'비율 t를 움직이거나 P₁·P₂를 끌어 보세요. 손잡이에 초점을 두면 방향키로 옮길 수 있습니다.'},
 en:{title:'The curve drafting table',tech:'De Casteljau construction',board:'Cubic Bézier construction with two movable handles',one:'3 first-level points',two:'2 second-level points',last:'Point on curve',handle:'Control point',ratio:'Interpolation fraction',hint:'Change t or drag P₁ and P₂. Focus a handle and use the arrow keys to move it.'},
 es:{title:'La mesa de trazado',tech:'Construcción de De Casteljau',board:'Curva de Bézier cúbica con dos controles móviles',one:'3 puntos del primer nivel',two:'2 del segundo nivel',last:'Punto de la curva',handle:'Punto de control',ratio:'Fracción de interpolación',hint:'Cambia t o arrastra P₁ y P₂. Selecciona un control con el teclado y muévelo con las flechas.'},
 'zh-Hans':{title:'曲线制图台',tech:'德卡斯特里奥构造',board:'带两个可移动控制点的三次贝塞尔曲线',one:'一级插值点 3 个',two:'二级插值点 2 个',last:'曲线上的点',handle:'控制点',ratio:'插值比例',hint:'调节 t 或拖动 P₁、P₂。用 Tab 选中控制点后，可用方向键移动。'}
};
const params=new URLSearchParams(location.search),requested=params.get('lang')||document.documentElement.lang;
const lang=Object.hasOwn(copy,requested)?requested:'ko',t=copy[lang];document.documentElement.lang=lang;document.title=t.title+' · MotionLab';
for(const el of document.querySelectorAll('[data-t]'))el.textContent=t[el.dataset.t];
const get=id=>document.getElementById(id),board=get('board'),range=get('ratio'),ns='http://www.w3.org/2000/svg';
range.setAttribute('aria-label',t.ratio);
const control=[[43,172],[133,34],[319,178],[439,56]],tags=['P₀','P₁','P₂','P₃'];
function add(parent,name,attributes){const n=document.createElementNS(ns,name);for(const [k,v] of Object.entries(attributes))n.setAttribute(k,v);parent.append(n);return n;}
const roots=control.map((point,i)=>{
 const g=add(get('roots'),'g',{'data-index':i});if(i===1||i===2){g.classList.add('handle');g.setAttribute('tabindex','0');g.setAttribute('role','group');g.setAttribute('aria-label',t.handle+' '+tags[i]);add(g,'circle',{r:15,fill:'transparent'});}
 add(g,'circle',{r:i===1||i===2?5.5:3.5,fill:i===1||i===2?'#fcfaec':'#405849',stroke:'#405849','stroke-width':1.8,class:'grip'});
 const label=add(g,'text',{x:i===3?-17:8,y:-8});label.textContent=tags[i];return g;
});
const qNodes=Array.from({length:3},()=>add(get('qPoints'),'rect',{x:-3.7,y:-3.7,width:7.4,height:7.4,fill:'#d5953d',stroke:'#644724','stroke-width':1}));
const rNodes=Array.from({length:2},()=>add(get('rPoints'),'path',{d:'M0 -5.2 5.2 0 0 5.2 -5.2 0Z',fill:'#69b59e',stroke:'#24574b','stroke-width':1}));
function mix(row,f){return row.slice(1).map((b,i)=>[row[i][0]+(b[0]-row[i][0])*f,row[i][1]+(b[1]-row[i][1])*f]);}
function place(el,p){el.setAttribute('transform','translate('+p.join(' ')+')');}
function render(){
 const v=+range.value/100,q=mix(control,v),r=mix(q,v),p=mix(r,v)[0];
 get('value').textContent=v.toFixed(2);get('polygon').setAttribute('points',control.join(' '));get('curve').setAttribute('d','M'+control[0]+' C'+control.slice(1).join(' '));
 get('qLine').setAttribute('points',q.join(' '));get('rLine').setAttribute('points',r.join(' '));
 roots.forEach((el,i)=>place(el,control[i]));qNodes.forEach((el,i)=>place(el,q[i]));rNodes.forEach((el,i)=>place(el,r[i]));place(get('result'),p);
 board.dataset.t=v.toFixed(2);board.dataset.point=p.map(n=>n.toFixed(3)).join(',');board.dataset.handles=control.slice(1,3).join(' ');
}
let frame=0,drag=null;
const media=matchMedia('(prefers-reduced-motion: reduce)'),reduced=()=>params.get('reduce')==='1'||document.documentElement.classList.contains('motion-reduced')||media.matches;
function preset(target){cancelAnimationFrame(frame);const from=+range.value,start=performance.now();
 function step(time){const u=reduced()?1:Math.min(1,(time-start)/490);range.value=Math.round(from+(target-from)*u*u*(3-2*u));render();if(u<1)frame=requestAnimationFrame(step);}
 step(start);}
function move(index,x,y){control[index]=[Math.max(22,Math.min(456,x)),Math.max(21,Math.min(199,y))];render();}
for(const h of roots.filter(n=>n.classList.contains('handle'))){
 const index=+h.dataset.index;
 h.addEventListener('pointerdown',e=>{if(!e.isPrimary||e.button!==0)return;cancelAnimationFrame(frame);drag={id:e.pointerId,index};board.setPointerCapture(e.pointerId);});
 h.addEventListener('keydown',e=>{const d={ArrowLeft:[-4,0],ArrowRight:[4,0],ArrowUp:[0,-4],ArrowDown:[0,4]}[e.key];if(d){e.preventDefault();move(index,control[index][0]+d[0],control[index][1]+d[1]);}});
}
board.addEventListener('pointermove',e=>{if(drag&&drag.id===e.pointerId){const p=new DOMPoint(e.clientX,e.clientY).matrixTransform(board.getScreenCTM().inverse());move(drag.index,p.x,p.y);}});
for(const event of ['pointerup','pointercancel','lostpointercapture'])board.addEventListener(event,e=>{if(drag?.id===e.pointerId)drag=null;});
range.oninput=()=>{cancelAnimationFrame(frame);render();};get('early').onclick=()=>preset(20);get('late').onclick=()=>preset(80);render();
</script></body></html>
```
