我想允许用户使用鼠标事件在HTML5画布上的MS Word中绘制类似肘部连接器的东西。我搜索了许多网站,但没有找到任何正确的解决方案。任何人都可以帮我提供代码或指出链接,如果有的话。 感谢
答案 0 :(得分:0)
您可以使用直线和二次曲线绘制弯头连接器,以弯曲弯头。
例如,您可以在画布的左上角绘制从[x:10,y:100]到[x:75,y:20]并且角半径为12的肘部,如下所示:< / p>
// top-left elbow from 10/100 to 75,20 with corner radius 12
ctx.beginPath();
ctx.moveTo(10,100);
ctx.lineTo(10,20+12);
ctx.quadraticCurveTo( 10,20, 10+12,20 );
ctx.lineTo(75,20);
ctx.strokeStyle=elbow.color;
ctx.lineWidth=elbow.linewi0dth;
ctx.stroke();
演示:http://jsfiddle.net/m1erickson/3cN7b/
以下是定义和绘制弯头连接器的示例代码:
<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" media="all" href="css/reset.css" /> <!-- reset css -->
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<style>
body{ background-color: ivory; }
#canvas{border:1px solid red;}
</style>
<script>
$(function(){
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var elbows=[];
elbows.push({
type:"topLeft",
start:{x:20,y:120},
end:{x:120,y:20},
cornerRadius:12,
color:"red",
linewidth:8
});
elbows.push({
type:"topRight",
start:{x:120,y:20},
end:{x:220,y:120},
cornerRadius:12,
color:"blue",
linewidth:8
});
elbows.push({
type:"bottomRight",
start:{x:220,y:120},
end:{x:120,y:220},
cornerRadius:12,
color:"green",
linewidth:8
});
elbows.push({
type:"bottomLeft",
start:{x:120,y:220},
end:{x:20,y:120},
cornerRadius:12,
color:"gold",
linewidth:8
});
drawElbows();
function drawElbows(){
for(var i=0;i<elbows.length;i++){
drawElbow(elbows[i]);
}
}
function drawElbow(elbow){
// starting elbow
ctx.beginPath();
ctx.moveTo(elbow.start.x,elbow.start.y);
// middle elbow
switch(elbow.type){
case "topLeft":
ctx.lineTo(elbow.start.x,elbow.end.y+elbow.cornerRadius);
ctx.quadraticCurveTo(
elbow.start.x,elbow.end.y,
elbow.start.x+elbow.cornerRadius,elbow.end.y
);
break;
case "topRight":
ctx.lineTo(elbow.end.x-elbow.cornerRadius,elbow.start.y);
ctx.quadraticCurveTo(
elbow.end.x,elbow.start.y,
elbow.end.x,elbow.start.y+elbow.cornerRadius
);
break;
case "bottomRight":
ctx.lineTo(elbow.start.x,elbow.end.y-elbow.cornerRadius);
ctx.quadraticCurveTo(
elbow.start.x,elbow.end.y,
elbow.start.x-elbow.cornerRadius,elbow.end.y
);
break;
case "bottomLeft":
ctx.lineTo(elbow.end.x+elbow.cornerRadius,elbow.start.y);
ctx.quadraticCurveTo(
elbow.end.x,elbow.start.y,
elbow.end.x,elbow.start.y-elbow.cornerRadius
);
break;
}
// ending elbow
ctx.lineTo(elbow.end.x,elbow.end.y);
ctx.strokeStyle=elbow.color;
ctx.lineWidth=elbow.linewi0dth;
ctx.stroke();
}
}); // end $(function(){});
</script>
</head>
<body>
<canvas id="canvas" width=300 height=300></canvas>
</body>
</html>