我使用以下代码绘制正方形。我是javascript的新手。谁能告诉我以下代码有什么问题?它没有绘制精确/正确的方形。正方形的边/长度必须是x和x之间的长度。年。我认为存在一些维度问题。请帮忙!
construct: function(pos,parent) {
obj=Object.create(parent);
obj.minx=obj.maxx=pos.x;
obj.miny=obj.maxy=pos.y;
if (fillColor!="inherit")
obj.fillStyle=fillColor;
if (strokeColor!="inherit")
obj.strokeStyle=strokeColor;
if (strokeThickness!="inherit")
obj.lineWidth=strokeThickness;
},
draw: function(selected) {
ctx.beginPath();
ctx.fillStyle=this.fillStyle;
ctx.strokeStyle=(selected) ?
"gray" : this.strokeStyle;
ctx.lineWidth=this.lineWidth;
ctx.rect(this.minx,this.miny,this.maxx,this.maxy);
ctx.fill();
if (selected) {
ctx.moveTo(this.minx,this.miny);
ctx.lineTo(this.maxx,this.maxy);
ctx.moveTo(this.minx,this.maxy);
ctx.lineTo(this.maxx,this.miny);
}
ctx.stroke();
},
mousedown: function(event) {
downPos=event;
square.construct(downPos,drawObject[containingBox4point(downPos)]);
inDrag=true;
},
mousemove: function(event) {
if (!inDrag)
{
drawPrevious();
drawCursor(event,containingBox4point(event));
return;
}
upPos=event;
if (upPos.x>downPos.x) {
obj.minx=downPos.x;
obj.maxx=upPos.x + Math.abs(obj.maxy - obj.miny);
}
else {
obj.minx=upPos.x;
obj.maxx=downPos.x + Math.abs(obj.maxy - obj.miny);
}
if (upPos.y>downPos.y) {
obj.miny=downPos.y;
obj.maxy=upPos.y + Math.abs(obj.maxx - obj.minx);
}
else {
obj.miny=upPos.y;
obj.maxy=downPos.y + Math.abs(obj.maxx - obj.minx);
}
drawPrevious();
obj.draw(containingBox(obj)==(-1));
drawCursor(event,containingBox4point(upPos));
}
答案 0 :(得分:11)
基于单选按钮模式在画布上绘制矩形或正方形
我提供这个解释,因为我尊敬地相信你的代码已经偏离了一点:)
简要教程
此代码使用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将设置为“square”
// use jQuery to set the modeName variable
$('input[name=mode]').click(function() {
modeName=$('input[name=mode]:checked').val();
});
侦听鼠标事件
当用户按下/释放鼠标按钮并移动鼠标时,使用jQuery监听。
收听鼠标事件:
// 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函数:
handleMouseDown:
// 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函数
handleMouseUp:
// called when the user releases the mouse button,
function handleMouseUp(e){
// the drag is over, clear the isDragging flag
isDragging=false;
}
当用户拖动时,会反复调用handleMouseMove函数:
handleMouseMove:
// 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个相等的边,因此在拖动正方形时,它可能会“跳”
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();
}
答案 1 :(得分:2)
由于我无法添加评论,因此我想为&#34; markE&#34;中的绘图方块的数学部分添加额外信息。 algorythm。
如果您使用:
var lengthX=Math.abs(mouseX-startX);
var lengthY=Math.abs(mouseY-startY);
if(lengthX<lengthY){ //changed this part
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);
}
你可以删除这个方形跳跃并获得更多MS Paintlike动作。
答案 2 :(得分:0)
使用Square
的简单Javascript<!DOCTYPE html>
<html>
<body>
<canvas id="myCanvas" width="300" height="150" style="border:1px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.</canvas>
<script>
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.rect(20, 20, 150, 100);
ctx.stroke();
</script>
</body>
</html>
如需更多设计,请点击此处:How to Create a Centered Square Crop