填充多边形区域Html5画布

时间:2013-07-23 15:01:20

标签: jquery html5 canvas

这是HTML代码

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.min.js"></script>    
<script src="http://d3lp1msu2r81bx.cloudfront.net/kjs/js/lib/kinetic-v4.5.4.min.js"></script>
<input type="button" value="draw" onclick="setdraw()" />
<input type="button" value="fill" onclick="setfill()" />
<div id="drawarea">
</div>

这是Javascript代码

var flag = false;
var pen_arr = [];
var drawble = true;
$(document).ready(function(){
    init();
});

function setfill(){
    drawble = false;
}

function setdraw(){
    drawble = true;
}

function init(){
    stage = new Kinetic.Stage({
        container: 'drawarea',
        width: 500,
        height: 800
    });

    background = new Kinetic.Rect({
        x: 0, 
        y: 0, 
        width: stage.getWidth(),
        height: stage.getHeight()
    });

    layer = new Kinetic.Layer();
    layer.add(background);

    stage.add(layer);

    stage.on("mousedown", mouseDown );
    stage.on("mousemove", mouseMove );
    stage.on("mouseup",   mouseUp );
}

function mouseDown(){

  if (drawble === true){   
    flag = true;
    var mousePos = stage.getMousePosition();
    var tmp_pen = new Kinetic.Line({
        points:[mousePos.x, mousePos.y, mousePos.x + 1, mousePos.y + 1 ],
        stroke: "blue",  
        strokeWidth: 3
    });
    layer.add(tmp_pen );    
    pen_arr.push(tmp_pen );
    layer.drawScene();   
  }else{
     flag = false;

    // in here i have to carry fill function
    // when i click in stage, i have to set the fill color in closed area after drawing pen
  }

}

function mouseMove(){
    if(flag === true ) {
        var mousePos = stage.getMousePosition();
        var tmp_pen = pen_arr[pen_arr.length - 1];
        var points = tmp_pen.getPoints();
        points.push({x:mousePos.x,y:mousePos.y});
        tmp_pen.setPoints(points);
        layer.drawScene(); 
    }
}

function mouseUp(){
    flag = false;    
}

请检查此结果。

在这里你可以检查一些图纸样品
有两个按钮“填充”和“绘制”
您可以通过单击“绘制”按钮来绘制笔 我们必须通过点击“填充”按钮来设置填充颜色 点击“填充”按钮后,我们可以点击舞台上的任意一点 那时,我们必须设置关闭区域的填充颜色

所以我的问题是“我必须在关闭的区域设置填充颜色”

1 个答案:

答案 0 :(得分:1)

我不打算给你代码 看看这个:

http://www.html5canvastutorials.com/tutorials/html5-canvas-shape-fill/