如何按比例在画布空间中创建两个或多个矩形?

时间:2014-01-15 15:58:58

标签: javascript html5 canvas draw

人!

我有一个问题。

我希望按比例在空间中创建两个或多个矩形。 所以,有一个画布在600x800px,我有一个200x400px的矩形,我需要当我点击一个按钮,在其他的一些空间创建更多的一个矩形。对于两个矩形,保持100x200和100x200。

有人吗? 谢谢!

1 个答案:

答案 0 :(得分:0)

您所要做的就是:

  • 保留Y坐标变量,
  • 在Y处绘制下一个矩形,
  • 按矩形高度增加Y(加上您想要的任意间距)

这是代码和演示:http://jsfiddle.net/m1erickson/czMXH/

<!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");

    var y=10;
    var spacer=8;

    $("#again").click(function(){

        ctx.fillStyle=randomColor();
        ctx.fillRect(10,y,100,66);
        ctx.strokeStyle="black";
        ctx.strokeRect(10,y,100,66);
        y+=66+spacer;

    });

    function randomColor(){ 
        return('#'+Math.floor(Math.random()*16777215).toString(16));
    }


}); // end $(function(){});
</script>

</head>

<body>
    <button id="again">Add</button><br>
    <canvas id="canvas" width=300 height=300></canvas>
</body>
</html>