簡體   English   中英

使用畫布在javascript中繪制一個正方形

[英]Draw a square in javascript using canvas

我使用以下代碼繪制一個正方形。 我是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));
      }

基於單選按鈕模式在畫布上繪制矩形或正方形

在此輸入圖像描述在此輸入圖像描述

我提供這個解釋,因為我尊敬地相信你的代碼已經偏離了一點:)

簡要教程

此代碼使用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監聽。

  • 當用戶按下鼠標按鈕時,將調用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。

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函數

  • 清除isDragging標志(拖動結束)

handleMouseUp:

// called when the user releases the mouse button,  

function handleMouseUp(e){

  // the drag is over, clear the isDragging flag

  isDragging=false;

}

當用戶拖動時,重復調用handleMouseMove函數:

  • 如果未設置isDragging標志,則退出。
  • 清除畫布以准備新定位的矩形/正方形。
  • 如果用戶想要一個矩形,則調用一個函數來繪制一個矩形。
  • 如果用戶想要一個正方形,則調用一個函數來繪制一個正方形。

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

由於我無法添加評論,我想從“markE”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動作。

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

有關更多設計,請單擊此處: 如何創建中心正方形裁剪

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM