【问题标题】:HTML/JS How to position a rectangle relative to 'any' side of the parent canvas elementHTML / JS如何相对于父画布元素的“任何”侧定位矩形
【发布时间】:2015-01-22 08:50:51
【问题描述】:

HTML/CSS 中,我们可以通过toprightleftbottom 将孩子与父母的任何一侧对齐

这可以应用于canvas 上的矩形、线条等吗? 或者他们是一种在定位中使用百分比的方法吗?

我的最终目标是获得一个矩形,其位置对齐到画布的右侧,并且在调整画布大小时保持原样。

我想不出办法来做到这一点。

这就是我正在使用的。

ctx.rect(20,20,150,100);

【问题讨论】:

  • 如果可能的话,可以发htmljs,创建stacksn-ps/jsfiddle吗?谢谢

标签: javascript jquery html canvas


【解决方案1】:

Html 和 CSS 可以重新定位子元素,因为这些子元素的定义保存在文档 Object 模型 (DOM) 中。

Html Canvas 元素不保存它在自身上绘制的任何矩形、线条等的定义。因此,它不能“召回”您的矩形来重新定位它。对于 Canvas,您的矩形在其位图显示上变成了不记得的像素。

要重新定位矩形,您必须使用代码手动“记住”其定义。这通常通过将矩形的定义保存在 javascript 对象中来完成,如下所示:

var myRect={
    x:20,
    y:20,
    width:150,
    height:100,
}

当您想要重新定位画布矩形时(例如当您希望它“粘贴”到调整大小的画布时),您:

  1. 调整画布大小。 (注意:调整画布元素的大小会自动清除其内容)。

  2. 计算新的 [x,y] 将使您的矩形“卡”在画布的右侧。如果您希望矩形贴在右侧,请重新计算:var newX=canvas.width-myRect.width

  3. myRect 中的 [x,y] 更改为新的 x,y 值。

  4. 使用 myRect 在新的所需位置重新绘制矩形。

这是带注释的示例代码和演示:

// canvas related variables
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var cw=canvas.width;
var ch=canvas.height;

// the definition of your rectangle 
// (this definition is used when your rectangle must be redrawn)
var myRect={
  x:20,
  y:20,
  width:150,
  height:100,
}

// call helper function to reset your rectangle's "x"
// so it's positioned to the right side
stickRight(myRect);

// call helper function to redraw your rectangle
redrawRect(myRect);

// listen for changes in the html slider that resizes the canvas
$myslider=$('#myslider');
$myslider.change(function(){

  // fetch the scaling factor the user has specified with the slider
  var scale=parseInt($(this).val());

  // resize the canvas to the specified size
  // NOTE: resizing the canvas automatically erases all content
  canvas.width=cw*scale/100;
  canvas.height=ch*scale/100;

  // again call helper function to reset your rectangle's "x"
  // so it's positioned to the right side
  stickRight(myRect);

  // call helper function to redraw your rectangle
  redrawRect(myRect);
});


function stickRight(rect){
  rect.x=canvas.width-myRect.width;
}

function redrawRect(rect){
  ctx.beginPath();
  ctx.rect(rect.x,rect.y,rect.width,rect.height);
  ctx.stroke()
}
body{ background-color: ivory; padding:10px; }
#canvas{border:1px solid red;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
Resize: <input id=myslider type=range min=0 max=200 value=100><br>
<canvas id="canvas" width=300 height=300></canvas>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-05-26
    • 2011-03-29
    • 1970-01-01
    • 2015-12-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多