基于单选按钮模式在画布上绘制矩形或正方形
我提供了这个解释,因为我恭敬地相信你的代码有点偏离了方向:)
一个简短的教程
此代码使用 jQuery 来消除不同 Web 浏览器之间的差异。
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
首先,获取canvas元素的引用
// get a reference to the canvas element
var canvas=document.getElementById("canvas");
为绘图创建一个画布上下文(称为 ctx):
// create a canvas context to draw stuff with
var ctx=canvas.getContext("2d");
在上下文中设置一些样式
// set the context's fill and stroke styles
ctx.fillStyle="skyblue";
ctx.strokeStyle="lightgray";
ctx.lineWidth=3;
保存网页上的画布位置。
这将在稍后用于计算鼠标位置。
// get the canvas's position on the page
var canvasOffset=$("#canvas").offset();
var offsetX=canvasOffset.left;
var offsetY=canvasOffset.top;
因为我们要拖动,所以设置变量来保存拖动的起始 XY
// set up variables to hold the mouse starting X/Y
// when the user drags the mouse
var startX;
var startY;
创建一个变量来指示我们是否正在拖动。
// indicate whether the user is dragging the mouse
var isDragging=false;
创建一个变量来指示我们应该绘制正方形还是矩形:
// set up a variable to determine whether to draw a square or a rectangle
var modeName="square";
此代码在用户单击“方形”或“矩形”单选按钮时设置 modeName 变量
如果用户单击“矩形”单选按钮,则 modeName 将设置为“矩形”
如果用户单击“方形”单选按钮,则 modeName 将设置为“方形”
// use jQuery to set the modeName variable
$('input[name=mode]').click(function() {
modeName=$('input[name=mode]:checked').val();
});
监听鼠标事件
使用 jQuery 监听用户何时按下/释放鼠标按钮并移动鼠标。
- 当用户按下鼠标按钮时,handleMouseDown 将被调用,
- 当用户释放鼠标按钮时将调用handleMouseUp,
- 用户移动鼠标时会重复调用handleMouseMove
监听鼠标事件:
// listen for mousedown, call handleMouseDown when it’s pressed
$("#canvas").mousedown(function(e){handleMouseDown(e);});
// listen for mouseup, call handleMouseUp when it’s released
$("#canvas").mouseup(function(e){handleMouseUp(e);});
// listen for mouse movements, call handleMouseMove when the mouse moves
$("#canvas").mousemove(function(e){handleMouseMove(e);});
当用户按下、释放和移动鼠标时进行处理——拖动!
当用户按下鼠标时,会调用 handleMouseDown 函数:
- 将鼠标起始位置存储在 startX 和 startY 中。
- 将 isDragging 标志设置为 true。
手柄鼠标下:
// called when user presses the mouse button down
// This is the start of a drag
function handleMouseDown(e){
// calculate the mouse position relative to the canvas
mouseX=parseInt(e.clientX-offsetX);
mouseY=parseInt(e.clientY-offsetY);
// store the starting mouse position
startX=mouseX;
startY=mouseY;
// set isDragging to indicate we’re starting a drag.
isDragging=true;
}
当用户释放鼠标按钮时,调用handleMouseUp函数
手柄鼠标向上:
// called when the user releases the mouse button,
function handleMouseUp(e){
// the drag is over, clear the isDragging flag
isDragging=false;
}
当用户拖动时,handleMouseMove函数被重复调用:
- 如果未设置 isDragging 标志,则退出。
- 清除画布以准备新定位的矩形/正方形。
- 如果用户想要一个矩形,调用一个函数来绘制一个矩形。
- 如果用户想要一个正方形,调用一个函数来绘制一个正方形。
手柄鼠标移动:
// called repeatedly when the user drags the mouse
function handleMouseMove(e){
// calculate the mouse position relative to the canvas
mouseX=parseInt(e.clientX-offsetX);
mouseY=parseInt(e.clientY-offsetY);
// if the user isn’t dragging, just exit
if( !isDragging ){ return; }
// clear the canvas in preparation for drawing a modified square/rectangle
ctx.clearRect(0,0,canvas.width,canvas.height);
// this switch decided if the user selected a rectangle or square for drawing
switch(modeName){
// the user clicked the rectangle radio button and modeName == “rectangle”
case "rectangle":
// call a function that draws a rectangle
drawRectangle(mouseX,mouseY);
break;
// the user clicked the rectangle radio button and modeName == “square”
case "square":
// call a function that draws a square
drawSquare(mouseX,mouseY);
break;
default:
break;
}
}
此函数从 startX/startY 到当前 mouseX/mouseY 绘制一个矩形
function drawRectangle(mouseX,mouseY){
var width=mouseX-startX;
var height=mouseY-startY;
ctx.beginPath();
ctx.rect(startX,startY,width,height);
ctx.fill();
ctx.stroke();
}
此函数从 startX/startY 向当前 mouseX/mouseY 绘制一个正方形
正方形的所有 4 个边将由以下公式确定:mouseX – startX
由于正方形必须强制 4 个相等的边,所以拖动正方形时,它可能会出现“跳跃”</p>
function drawSquare(mouseX,mouseY){
var width=Math.abs(mouseX-startX)*(mouseX<startX?-1:1);
var height=Math.abs(width)*(mouseY<startY?-1:1);
ctx.beginPath();
ctx.rect(startX,startY,width,height);
ctx.fill();
ctx.stroke();
}
这是代码和小提琴:http: //jsfiddle.net/m1erickson/myHDW/
<!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:20px;}
#canvas{border:1px solid red;}
input{width:15px;}
</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;
var startX;
var startY;
var isDown=false;
ctx.fillStyle="skyblue";
ctx.strokeStyle="lightgray";
ctx.lineWidth=3;
var modeName="square";
$('input[name=mode]').click(function() {
modeName=$('input[name=mode]:checked').val();
console.log(modeName);
});
function handleMouseDown(e){
mouseX=parseInt(e.clientX-offsetX);
mouseY=parseInt(e.clientY-offsetY);
// Put your mousedown stuff here
startX=mouseX;
startY=mouseY;
isDown=true;
}
function handleMouseUp(e){
mouseX=parseInt(e.clientX-offsetX);
mouseY=parseInt(e.clientY-offsetY);
$("#uplog").html("Up: "+ mouseX + " / " + mouseY);
// Put your mouseup stuff here
isDown=false;
}
function handleMouseMove(e){
mouseX=parseInt(e.clientX-offsetX);
mouseY=parseInt(e.clientY-offsetY);
// Put your mousemove stuff here
if(!isDown){return;}
ctx.clearRect(0,0,canvas.width,canvas.height);
switch(modeName){
case "rectangle":
drawRectangle(mouseX,mouseY);
break;
case "square":
drawSquare(mouseX,mouseY);
break;
default:
break;
}
}
function drawRectangle(mouseX,mouseY){
var width=mouseX-startX;
var height=mouseY-startY;
ctx.beginPath();
ctx.rect(startX,startY,width,height);
ctx.fill();
ctx.stroke();
}
function drawSquare(mouseX,mouseY){
var width=Math.abs(mouseX-startX)*(mouseX<startX?-1:1);
var height=Math.abs(width)*(mouseY<startY?-1:1);
ctx.beginPath();
ctx.rect(startX,startY,width,height);
ctx.fill();
ctx.stroke();
}
$("#canvas").mousedown(function(e){handleMouseDown(e);});
$("#canvas").mousemove(function(e){handleMouseMove(e);});
$("#canvas").mouseup(function(e){handleMouseUp(e);});
}); // end $(function(){});
</script>
</head>
<body>
<p>Note: the square's side length is determined</p>
<p>by mouseX minus startingX.</p>
<p>As a result, the square may "jump" as you</p>
<p>move left or above the starting point.</p>
<canvas id="canvas" width=300 height=300></canvas><br>
<input type="radio" id="rect" name="mode" value="rectangle" />
<label for="rect">Rectangle</label>
<input type="radio" id="sqr" name="mode" value="square" checked="checked" />
<label for="sqr">Square</label>
</body>
</html>
[补充:Math.abs(mouseX-startX) 和 Math.abs(mouseY-startY) 的平方更长]
这种替代 drawSquare() 将计算 x-drag 和 y-drag 中较长的一个,并将该计算用作正方形 4 个边的长度:
function drawSquare(mouseX,mouseY){
var lengthX=Math.abs(mouseX-startX);
var lengthY=Math.abs(mouseY-startY);
if(lengthX>lengthY){
var width=lengthX*(mouseX<startX?-1:1);
var height=lengthX*(mouseY<startY?-1:1);
}else{
var width=lengthY*(mouseX<startX?-1:1);
var height=lengthY*(mouseY<startY?-1:1);
}
ctx.beginPath();
ctx.rect(startX,startY,width,height);
ctx.fill();
ctx.stroke();
}