index.html 2.61 KB
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 
	<title>无标题</title>
    <style>
        .xnCanvas{
            width: 1024px;
            height: 768px;
            border: 1px solid #dcdcdc;
        }
    </style>
</head>
<body>
<h1>HTML Canvas Event Demo - By Gloomy Fish</h1>
<pre>Press W, A, S, D keys to move</pre>


<div class="xn-canvas">
    <canvas id="xnCanvas" tabindex="0" width="1024" height="768"></canvas>
</div>

<script type="text/javascript">
    var canvasData=[
        [{x:20,y:20},{x:120,y:20},{x:120,y:120},{x:20,y:120}],
        [{x:120,y:120},{x:120,y:220},{x:220,y:220},{x:220,y:120}],
        [{x:330,y:320},{x:600,y:800},{x:400,y:800},{x:220,y:120},{x:800,y:60}]
    ];
    var setMap=function(sample,data,state,loc){
        this.state=state;
        sample.beginPath();
        for(var j=0;j<data.length;j++){
           if(j==0){
                sample.moveTo(data[j].x,data[j].y);
            }else{
                 sample.lineTo(data[j].x,data[j].y);
            }
        }
        sample.closePath();
        //填充
        var position=false;
            if(loc){
                position=sample.isPointInPath(loc.x,loc.y);
            }
        if(this.state || position){
            sample.fillStyle="#000000";
            sample.strokeStyle="#ff0000";
        }else{
            sample.fillStyle="#ffffff";
            sample.strokeStyle="#ff0000";
        }
        sample.stroke();
        sample.fill();
    };

    function draw(loc){
        var canvas = document.getElementById('xnCanvas');
        if(canvas.getContext) {
            var sample = canvas.getContext('2d');
            for(var i = 0; i < canvasData.length; i++) {
                var state=false;
              /*  if(2 ==(i+1)){
                    state=true;
                }*/
                var c = new setMap(sample,canvasData[i],state,loc);
            }
        }
    }

    function getPointOnCanvas(canvas, x, y) {
        var bbox = canvas.getBoundingClientRect();
        return { x: x - bbox.left * (canvas.width / bbox.width),
            y: y - bbox.top * (canvas.height / bbox.height)
        };
    }


    function doMouseDown(event) {
        var x = event.pageX;
        var y = event.pageY;
        var canvas = event.target;
        var loc = getPointOnCanvas(canvas, x, y);
        console.log("mouse down at point( x:" + loc.x + ", y:" + loc.y + ")");
        draw(loc);
    }



    function main(){

        var canvas = document.getElementById("xnCanvas");
        draw();
        canvas.addEventListener("mousedown", doMouseDown, false);

    }
    main();

</script>
</body>
</html>