我试图在JCanvas中使用鼠标事件在画布上绘制线条和矩形

时间:2014-03-04 04:26:31

标签: javascript jquery html5 canvas jcanvas

我正在尝试使用JCanvas中的鼠标事件在画布上绘制线条和矩形。这是我的代码

   <!DOCTYPE html>
   <html>
      <head>
          <script type="text/javascript" src="http://code.jquery.com/jquery-  1.10.2.min.js"></script>
          <script type="text/javascript" src="http://calebevans.me/projects/jcanvas/resources/jcanvas/jcanvas.js"></script>
    </head>
    <body>
         <div id="tools">&nbsp; &nbsp;
            <button id = "rectangle" type = "button"title="Rectangle"style="border:0;padding:0;">
                <img src="rect.jpg" width="40" height="30"/>
            </button>
            <button id = "line" type="button" title="Line" style="border:0;padding:0;">
                <img src="line.jpg" width="40" height="30" />
            </button>
        </div>
        <div id="sketch">
            <canvas id="paint">
            </canvas>
        </div>
        <script>
            var tool = ' ';
    $('#tools button').on('click', function()
    {
        tool = $(this).attr('id');
        console.log(tool);
    });
    var canvas = document.getElementById('paint');
    var ctx = canvas.getContext('2d');
    var sketch = document.getElementById('sketch');
    var sketch_style = getComputedStyle(sketch);
    canvas.width = parseInt(sketch_style.getPropertyValue('width'));
    canvas.height = parseInt(sketch_style.getPropertyValue('height'));
    var isText = false;
    // Creating a tmp canvas
    var tmp_canvas = document.createElement('canvas');
    var tmp_ctx = tmp_canvas.getContext('2d');
    tmp_canvas.id = 'tmp_canvas';
    tmp_canvas.width = canvas.width;
    tmp_canvas.height = canvas.height;
    sketch.appendChild(tmp_canvas);
    var mouse = {x: 0, y: 0};
    var start_mouse = {x: 0, y: 0};
    var last_mouse = {x: 0, y: 0};
    if ( tool == 'line')
    {
        $('canvas').draw({
            $('#line').click(function () 
            {
                mousemove: function (e)
                {
                    mouse.x = typeof e.offsetX !== 'undefined' ? e.offsetX : e.layerX;
                    mouse.y = typeof e.offsetY !== 'undefined' ? e.offsetY : e.layerY;
                },
                mousedown: function (e)
                {
                    mouse.x = typeof e.offsetX !== 'undefined' ? e.offsetX : e.layerX;
                    mouse.y = typeof e.offsetY !== 'undefined' ? e.offsetY : e.layerY;
                    start_mouse.x = mouse.x;
                    start_mouse.y = mouse.y;
                    canvas.addEventListener('mousemove',onLinePaint,false);
                    onLinePaint();
                },
                mouseup: function ()
                {
                    canvas.removeEventListener('mousemove',onLinePaint,false);
                    ctx.drawImage(canvas,0,0);
                    ctx.clearRect(0,0,canvas.width,canvas.height);
                }
            });
        });
    }
    if (tool == 'rectangle')
    {

        $('canvas').draw({
            $('#rectangle').click(function () 
            {
                mousemove: function (e)
                {
                    mouse.x = typeof e.offsetX !== 'undefined' ?   e.offsetX : e.layerX;
                    mouse.y = typeof e.offsetY !== 'undefined' ? e.offsetY : e.layerY;
                },
                mousedown: function (e)
                {
                    mouse.x = typeof e.offsetX !== 'undefined' ? e.offsetX : e.layerX;
                    mouse.y = typeof e.offsetY !== 'undefined' ? e.offsetY : e.layerY;
                    start_mouse.x = mouse.x;
                    start_mouse.y = mouse.y;
                    canvas.addEventListener('mousemove',onRectPaint,false);
                    onRectPaint();
                },
                mouseup: function ()
                {
                    canvas.removeEventListener('mousemove',onRectPaint,false);
                    ctx.drawImage(canvas,0,0);
                    ctx.clearRect(0,0,canvas.width,canvas.height);
                }
            });
        });
    }
    var onLinePaint = function ()
    {
        // Tmp canvas is always cleared up before drawing.
        ctx.clearRect(0, 0, canvas.width, canvas.height);
        ctx.beginPath();
        ctx.moveTo(start_mouse.x, start_mouse.y);
        ctx.lineTo(mouse.x, mouse.y);
        ctx.stroke();
        ctx.closePath();
    };
    var onRectPaint = function()
    {
        // Tmp canvas is always cleared up before drawing.
        ctx.clearRect(0, 0, canvas.width, canvas.height);
        var x = Math.min(mouse.x, start_mouse.x);
        var y = Math.min(mouse.y, start_mouse.y);
        var width = Math.abs(mouse.x - start_mouse.x);
        var height = Math.abs(mouse.y - start_mouse.y);
        ctx.strokeRect(x, y, width, height);
    };
        </script>
    </body>
</html>

但我没有得到预期的输出。你可以告诉我在上面的代码中我做错了什么。 提前谢谢。

1 个答案:

答案 0 :(得分:0)

  

抱歉,我不能写完整个代码,但我相信这可能会有所帮助

     

注意:请参考函数getImageData,putImageData

<强>画布

  

将图片加载到画布

var editor = document.getElementById("editor"), 
   context = editor.getContext("2d")   ,

//create/load image to canvas
image = $("<img/>", { 
                     src : "img/man.png", 
                    load : function() { 
                        context.drawImage(this, 0, 0);   
                    } 
        })

抓住鼠标

  

检测鼠标保持

editor.onmousedown = function(){
    var clicking = true;
    this.onmouseup = function(){
        clicking = false
    }
    this.onmousemove=function(e){

        if(!clicking)  
            return

        //code goes here
        var pos    = findPos(this);
    }
}

找到位置

  

找到鼠标位置

function findPos(obj) {
    var curleft = 0, curtop = 0;
    if (obj.offsetParent) {
        do {
            curleft += obj.offsetLeft;
            curtop += obj.offsetTop;
        } while (obj = obj.offsetParent);
        return { x: curleft, y: curtop };
    }
    return undefined;
}

订单

function(fromX,fromY,toX,toY){
     // line from
     ctx.moveTo(fromX,fromY);

     // line to
     ctx.lineTo(toX,toY);

     // color
     ctx.strokeStyle = "#4bf";

     // line width
     ctx.lineWidth = 1;

     // draw it
     ctx.stroke();

}

<强>矩形

// color
ctx.fillStyle = "#FF0000";
// put coordinates to fill
context.fillRect(20,20,150,100);