中心在html画布中对齐多边形

时间:2014-02-26 14:30:30

标签: javascript html5-canvas

我正在使用我找到的代码在画布中动态绘制多边形。 (坐标由用户提供)

https://stackoverflow.com/a/4841057/1667856

是否可以在创建之后/之前将此多边形移动到画布的中心?

我发现你可以使用canvas translate()方法来移动形状,但我似乎无法弄清楚如何重新计算坐标,以便多边形将自动出现在画布的中间而不是它的原始坐标。

1 个答案:

答案 0 :(得分:1)

正如您可能已经发现的那样,html canvas只是一个像素图。

您在画布上绘制的形状就像干漆一样。它们不能移动或重塑成另一种形状。

“移动”形状的典型方法是清除画布并使用不同的坐标重绘相同的形状。

您可以通过向所有多边形坐标添加offsetX和offsetY来创建这些坐标。

或者(更简单地说)你可以翻译坐标。

重要提示:context.translate不只是移动多边形的坐标。它会更改所有 NEW 图形的每个坐标。

ctx.translate(50,50)将画布的原点“移动”到50,50。这意味着如果你开始在5,5处绘制多边形,你将在视觉上开始以50 + 5,50 + 5绘制。

以下是示例代码和演示:http://jsfiddle.net/m1erickson/2Gm73/

<!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; }
    canvas{border:1px solid red;}
</style>
<script>
$(function(){

    var canvas=document.getElementById("canvas");
    var ctx=canvas.getContext("2d");


    // calculate the middle of the canvas
    var centerX=canvas.width/2;
    var centerY=canvas.height/2;

    // just for testing: draw crosshairs on center canvas
    ctx.beginPath();
    ctx.moveTo(centerX,0);
    ctx.lineTo(centerX,canvas.height);
    ctx.moveTo(0,centerY);
    ctx.lineTo(canvas.width,centerY);
    ctx.stroke();

    // define some points for your polygon
    var poly=[ 5,5, 100,50, 50,100, 10,90 ];

    // save the canvas context in its untranslated state
    ctx.save();

    // translate the canvas
    // the context now uses centerX,centerY as its 0,0 origin
    ctx.translate(centerX,centerY);

    // draw the polygon
    ctx.beginPath();
    ctx.moveTo(poly[0], poly[1]);
    for(var i=2;i<poly.length;i+=2){
        ctx.lineTo( poly[i] , poly[i+1] )
    }
    ctx.closePath();
    ctx.fillStyle = '#f00';
    ctx.fill();

    // restore the context to its untranslated state
    // (otherwise all further drawings will be "moved"
    // just like this polygon
    ctx.restore();

}); // end $(function(){});
</script>
</head>
<body>
    <canvas id="canvas" width=300 height=300></canvas>
</body>
</html>

如果希望多边形在画布中以视觉方式居中,则还必须计算多边形中心的偏移量:

// calc the max values of x,y in the polygon and divide by 2

var centerPolyX = 100/2;  // max x comes from coordinate 100,50
var centerPolyY = 100/2;  // max y comes from coordinate 50,100

然后转换为中心画布减去多边形中心:

// move to center canvas
// but then move left and up by half the polygon's size

ctx.translate(centerX-centerPolyX,centerY-centerPolyY);