3

我正在使用以下代码绘制一个正方形。我是 JavaScript 新手。谁能告诉我以下代码有什么问题?它没有画出精确/正确的正方形。正方形的边/长度必须是 x 和 y 之间较长的那个。我认为存在一些维度问题。请帮忙!

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));
      }
4

3 回答 3

15

基于单选按钮模式在画布上绘制矩形或正方形

在此处输入图像描述在此处输入图像描述

我提供了这个解释,因为我恭敬地相信你的代码有点偏离了方向:)

一个简短的教程

此代码使用 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函数

  • 清除 isDragging 标志(拖动结束)

手柄鼠标向上:

// 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();
    }
于 2013-07-29T20:38:06.553 回答
2

由于我无法添加评论,我想为“markE”算法中绘制正方形的数学部分添加额外信息。

如果您使用:

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 动作。

于 2015-04-17T11:48:15.427 回答
-1

这是制作 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>

有关更多设计,请单击此处:如何创建居中的方形裁剪

于 2015-06-13T05:29:47.037 回答