我在页面上画一条直线
方法很简单context.beginPath();
context.moveTo(10, 20);
context.lineTo(100, 120);
context.stroke();
现在我想获取该条线上所有的点坐标。是否可以?
HTML5 有相应的canvas API吗?急求大神canvashtml5apijavascript
方法很简单context.beginPath();
context.moveTo(10, 20);
context.lineTo(100, 120);
context.stroke();
现在我想获取该条线上所有的点坐标。是否可以?
HTML5 有相应的canvas API吗?急求大神canvashtml5apijavascript
<html>
<head>
<meta charset="gb3212">
<style type="text/css">
body{margin:0;}
canvas{margin: 0px;}
</style>
</head>
<body >
<style>
#canvas{
position: absolute;
left:50px;
top:50px;
}
#div1{
position: absolute;
background-color:blue;
width:5px;
height:5px;
}
</style>
<div id="div1"></div>
<canvas id="canvas" width="200" height="200" style="border: 1px solid #ccc;"></canvas>
<button id="bnt" onclick="play()">沿着 线运动</button>
<script>
var canvas=document.getElementById('canvas');
var context=canvas.getContext('2d');
var ctx=context;
var bnt=document.getElementById('bnt');
var isDraw=0,drawIndex=0,drawPs=[];
var p1={x:100,y:10},p2={x:15,y:100 };
context.strokeStyle = "red";
context.beginPath();
context.moveTo(p1.x,p1.y);
context.lineTo(p2.x,p2.y);
context.stroke();
//通过坐标计算
function getPs2(x1,y1,x2,y2){
var ps=[];
var _x=Math.abs(x1-x2),_y=Math.abs(y1-y2),
x_= x1>x2?0:1, y_= y1>y2?0:1;
var L= Math.min(_x,_y);
var xs=[x1,x2].sort(c),ys=[y1,y2].sort(c);
for(var i=0;i<=L;i++){
var x =parseInt(_x/L *i) , y=parseInt(_y/L *i);
ps.push( [ (x_?x+xs[0]:xs[1]-x ), (y_?y+ys[0]:ys[1]-y ) ] )
}
return ps;
function c(a,b){return a-b};
}
//取红色坐标
function getPs(ctx,W,H){
var i=0,ps=[] ;
var md= ctx.getImageData(0,0,W,H);
for(var y=0;y< W;y++){
for(var x=0;x< H;x++ ){
i=(x+y*W)*4;
if( md.data[i] ) ps.push([x,y]);
}
}
return ps;
} //播放路径动画
var playTir;
function play(){
var ps=getPs2(p1.x,p1.y,p2.x,p2.y);
if(!ps.length) return;
var left=canvas.offsetLeft,top=canvas.offsetTop;
var L=ps.length;
playTir=setInterval(function(){
if( (L-=2)<=0 ) return clearInterval(playTir);
div1.style.left=(ps[L][0]+left)+'px'
div1.style.top=(ps[L][1]+top)+'px'
},1);
}
</script>
</body>
</html>