要在两点之间逐步绘制一条线,您需要在两点之间插入 XY 值
// define the line
var startX=50;
var startY=150;
var endX=250;
var endY=50;
var dx=endX-startX;
var dy=endY-startY;
function lineXY(percent) {
// find the XY that’s a percentage of the way between start and end points
percent/=100;
currentX = startX + dx*percent;
currentY = startY + dy*percent;
// and then draw the line
ctx.clearRect(0,0,canvas.width,canvas.height);
ctx.beginPath();
ctx.moveTo(startX,startY);
ctx.lineTo(currentX,currentY);
ctx.stroke();
}
这是代码和小提琴:http: //jsfiddle.net/m1erickson/9tU9E/
<!doctype html>
<html lang="en">
<head>
<style>
body{ background-color: ivory; }
#wrapper{ position:relative; }
canvas{ position:absolute; left:40px; top:5px; border:1px solid red;}
#amount{ position:absolute; left:1px; top:5px; margin-bottom:15px; width:23px; border:0; color:#f6931f; font-weight:bold; }
#slider-vertical{ position:absolute; left:5px; top:40px; width:15px; height:225px; border:0px; color:#f6931f; font-weight:bold; }
</style>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<script>
$(function() {
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
$( "#slider-vertical" ).slider({
orientation: "vertical",
range: "min",
min: 0,
max: 100,
value: 50,
slide: function( event, ui ) {
$( "#amount" ).val( ui.value );
lineXY(ui.value);
}
});
$( "#amount" ).val( $( "#slider-vertical" ).slider( "value" ) );
var startX=50;
var startY=150;
var endX=250;
var endY=50;
var dx=endX-startX;
var dy=endY-startY;
ctx.strokeStyle="green";
ctx.lineWidth=5;
lineXY(50);
//
function lineXY(percent) {
percent/=100;
currentX = startX + dx*percent;
currentY = startY + dy*percent;
ctx.clearRect(0,0,canvas.width,canvas.height);
ctx.beginPath();
ctx.moveTo(startX,startY);
ctx.lineTo(currentX,currentY);
ctx.stroke();
ctx.beginPath();
ctx.arc(startX,startY,5,0,Math.PI*2,false);
ctx.closePath();
ctx.fill();
ctx.beginPath();
ctx.arc(endX,endY,5,0,Math.PI*2,false);
ctx.closePath();
ctx.fill();
}
}); // end $(function(){});
</script>
</head>
<body>
<div id="wrapper">
<input type="text" id="amount" />
<div id="slider-vertical"></div>
<canvas id="canvas" width=300 height=300></canvas>
</div>
</body>
</html>