您可以使用画布的“翻译”功能来绘制您的圆圈组,而无需重新计算!
当您使用“翻译”时,组的位置变得更简单。
翻译只是将整个组拖到画布上的新位置 的“幕后”数学 。
您不必为每个圈子单独计算。相反,您只需进行翻译,然后绘制圆圈,就好像它们处于起始位置一样。
这是隐含翻译的方法:
// do a translate to mouseX,mouseY
// all draws will be now be done RELATIVE to mouseX,mouseY
// so if we ctx.translate(100,100)
// then a ctx.rect(0,0,10,10) will actually be drawn at 100,100
ctx.translate(mouseX,mouseY);
// draw the ball group
// notice we didn't have to calculate ANY new positions!!
drawBallGroup();
// translate back after we're done
ctx.translate(-mouseX,-mouseY);
这是代码和小提琴:http: //jsfiddle.net/m1erickson/4rJgw/
<!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; padding:10px; }
canvas{border:1px solid red;}
</style>
<script>
$(function(){
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var canvasOffset=$("#canvas").offset();
var offsetX=canvasOffset.left;
var offsetY=canvasOffset.top;
drawBallGroup();
function drawBallGroup(){
drawBall(8,10,5,"red");
drawBall(20,15,10,"green");
drawBall(25,25,8,"blue");
drawBall(5,22,10,"orange");
drawBall(18,30,10,"black");
}
function drawBall(x,y,radius,color){
ctx.beginPath();
ctx.fillStyle=color;
ctx.arc(x,y,radius, 0, 2 * Math.PI, false);
ctx.fill();
}
function handleMouseDown(e){
mouseX=parseInt(e.clientX-offsetX);
mouseY=parseInt(e.clientY-offsetY);
// clear the canvas
ctx.clearRect(0,0,canvas.width,canvas.height);
// do a translate to mouseX,mouseY
// all draws will be now be done RELATIVE to mouseX,mouseY
// so if we ctx.translate(100,100)
// then ctx.rect(0,0,10,10) will actually be drawn at 100,100
ctx.translate(mouseX,mouseY);
// draw the ball group
// notice we didn't have to calculate ANY new positions!!
drawBallGroup();
// translate back after we're done
ctx.translate(-mouseX,-mouseY);
}
$("#canvas").mousedown(function(e){handleMouseDown(e);});
}); // end $(function(){});
</script>
</head>
<body>
<p>Click to move the ball group to a new location</p>
<p>WITHOUT recalculating each new ball position!</p><br/>
<canvas id="canvas" width=400 height=500></canvas>
</body>
</html>