簡體   English   中英

使用HTML5在畫布的中心設置兩個畫布正方形

[英]Set two canvas squares to the center of a canvas with HTML5

我有兩個要放置在畫布上的框要居中。 您可以在JS小提琴上查看此內容: http : //jsfiddle.net/FVU47/5/

我的畫布具有1000高度和1000寬度,如下所示:

<canvas id="myCanvas" width="1000" height="1000" style="border:3px solid #385D8A; outline:1px solid #7592B5; margin-left: 0px; margin-top: 0px; background-color: #B9CDE5"></canvas> 

然后,我嘗試使用以下代碼將兩個框居中,這會將box1或box2放在畫布的中心,具體取決於我單擊的是“轉到框1”還是“轉到框2”(請參見JSFiddle結果象限的底部:

$(document).ready(function(){
  $("#box1click").click(function(){
    if (rect1.x <= 500) {
      positionWidthSet = Math.abs(rect1.x - canvas.width/2) + rect1.x;
    }
    else{
      positionWidthSet = Math.abs(Math.abs(rect1.x - canvas.width/2) + rect1.x)
    }
    if (rect1.y >= 500) {
      positionHeightSet = Math.abs(rect1.y -canvas.height/2);
    }
    else{
      positionHeightSet = Math.abs(Math.abs(rect1.y - canvas.height/2) + rect1.y);
    }

    positionCanvasContext(positionWidthSet,positionHeightSet);
  });
});


$(document).ready(function(){
  $("#box2click").click(function(){
     if (rect2.x <= 500) {
      positionWidthSet = Math.abs(rect2.x - canvas.width/2) + rect2.x;
    }
    else{
      positionWidthSet = Math.abs(Math.abs(rect2.x - canvas.width/2) + rect2.x)
    }
    if (rect2.y >= 500) {
      positionHeightSet = Math.abs(rect2.y -canvas.height/2);
    }
    else{
      positionHeightSet = Math.abs(Math.abs(rect2.y - canvas.height/2) + rect2.y);
    }

    positionCanvasContext(positionWidthSet,positionHeightSet);
  });
});

當前,單擊“轉到框1”或“轉到框2”不會使畫布圍繞框1或框2居中,即使在控制台中嘗試使用我的公式似乎表明不是這樣。

這是一種方法: http : //jsfiddle.net/m1erickson/GpMsk/

將所有矩形放置在數組中:

var rects=[];

rects.push({
  x: 103,
  y: 262,
  w: 200,
  h: 100,
  fillStyle: 'red',
  hovered: false
});

rects.push({
  x: 484,
  y: 170,
  w: 200,
  h: 100,
  fillStyle: 'blue',
  hovered: false
});

創建一個draw()函數來繪制rects []數組中的所有rect

用指定的x / y偏移其原始x / y繪制所有矩形:

function draw(offsetX,offsetY){
    ctx.clearRect(0,0,canvas.width,canvas.height);
    for(var i=0;i<rects.length;i++){
        var r=rects[i];
        ctx.fillStyle=r.fillStyle;
        ctx.fillRect(r.x+offsetX,r.y+offsetY,r.w,r.h);
    }
}

單擊按鈕時,計算將指定矩形拉到畫布中心所需的偏移量

然后使用計算的偏移量重畫所有矩形。

var centerX=canvas.width/2;
var centerY=canvas.height/2;

function centerThisRect(rectsIndex){
    var r=rects[rectsIndex];
    var offsetX=centerX-r.x-r.w/2;
    var offsetY=centerY-r.y-r.h/2;
    draw(offsetX,offsetY);
}

暫無
暫無

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

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