鼠标移动时在画布上显示矩形

时间:2016-10-26 11:03:18

标签: javascript jquery html canvas



我想在画布上绘制矩形。下面的代码工作正常,除非我绘制矩形时它不会显示鼠标移动时的路径。当我离开鼠标时,在画布上可以看到矩形。

请帮忙,

谢谢



var canvas, ctx, flag = false,
        prevX = 0,
        currX = 0,
        prevY = 0,
        currY = 0,
        currShape = 'rectangle',
        mouseIsDown = 0,
        startX, endX, startY, endY,
        dot_flag = false;

    var x = "white",
        y = 2;
   
    function init() {
        canvas = document.getElementById('can');
        ctx = canvas.getContext("2d");
        var imageObj = new Image(); //Canvas image Obj

        imageObj.onload = function() {
            ctx.drawImage(imageObj, 69, 50);    //Load Image on canvas
        };
        imageObj.src = 'http://www.html5canvastutorials.com/demos/assets/darth-vader.jpg'; //Load Image 

        w = canvas.width;   // Canvas Width
        h = canvas.height;  // Canvas Height
        //Check Shape to be draw
        eventListener();

    }
    function eventListener(){
        if(currShape=='rectangle'){
            canvas.addEventListener("mousedown",function (e) { 
                mouseDown(e);
            }, false);
            canvas.addEventListener("mousemove",function (e){
                mouseXY(e);
            }, false);
            canvas.addEventListener("mouseup", function (e){ 
                mouseUp(e);
            }, false);
        }
    }

function mouseUp(eve) {
    if (mouseIsDown !== 0) {
        mouseIsDown = 0;
        var pos = getMousePos(canvas, eve);
        endX = pos.x;
        endY = pos.y;
        if(currShape=='rectangle')
        {
            drawSquare(); //update on mouse-up
        }
    }
}

function mouseDown(eve) {
    mouseIsDown = 1;
    var pos = getMousePos(canvas, eve);
    startX = endX = pos.x;
    startY = endY = pos.y;
    if(currShape=='rectangle')
    {
        drawSquare(); //update on mouse-up
    }
}

function mouseXY(eve) {
    if (mouseIsDown !== 0) {
        var pos = getMousePos(canvas, eve);
        endX = pos.x;
        endY = pos.y;
        //drawSquare();
    }
}

function drawSquare() {
    // creating a square
    var w = endX - startX;
    var h = endY - startY;
    var offsetX = (w < 0) ? w : 0;
    var offsetY = (h < 0) ? h : 0;
    var width = Math.abs(w);
    var height = Math.abs(h);

               
    ctx.beginPath();
    ctx.globalAlpha=0.7;
    ctx.rect(startX + offsetX, startY + offsetY, width, height);
    ctx.fillStyle = x;
    ctx.fill();
    ctx.lineWidth = y;
    ctx.strokeStyle = x;
    ctx.stroke();
}

function getMousePos(canvas, evt) {
    var rect = canvas.getBoundingClientRect();
    return {
        x: evt.clientX - rect.left,
        y: evt.clientY - rect.top
    };
}
&#13;
.colortool div {
        width: 15px;
        height: 15px;
        float: left;
        margin-left: 2px;
    }
    .clear {
      clear: both;
    }
&#13;
<!DOCTYPE HTML>
<html>
    <body onload="init()">
     <div class="canvasbody">
     <canvas id="can" width="400" height="400" style="border:1px dotted #eee;"></canvas>
     </div>
    </body>
    </html>
&#13;
&#13;
&#13;

4 个答案:

答案 0 :(得分:0)

在某种程度上,您需要跟踪对在画布上绘制的形状所做的更改。在您的情况下,您将首先创建一个非常小的矩形,然后在拖动过程中根据鼠标位置进行缩放。

目前,您只有一个绘制全新矩形但不考虑任何先前“状态”的函数。

我发现这个blogpost可能会有所帮助。它没有特别解释扩展,但它可以帮助我们背后的基本概念,所以我认为这将是一个很好的方法来找到合适的解决方案。

答案 1 :(得分:0)

因为我们使用它的id在DOM中找到canvas标签,然后将画布的绘图上下文设置为2D。这里有两件事是重要的是存储信息,因为我们绘制recatangle和bolean来检查用户是否正在绘制矩形。 您可以访问以下链接:Drawing a rectangle using click, mouse move, and click Draw on HTML5 Canvas using a mouse 检查给定链接中的js小提琴。 希望这会对你有帮助..

答案 2 :(得分:0)

这是你的新JavaScript

var canvas, cnvHid, cnvRender, ctx, flag = false,
        prevX = 0,
        currX = 0,
        prevY = 0,
        currY = 0,
        currShape = 'rectangle',
        mouseIsDown = 0,
        startX, endX, startY, endY,
        dot_flag = false;

    var x = "white",
        y = 2;

    function init() {
        canvas = document.getElementById('can');
        cnvHid = document.getElementById( "canHid" );
        cnvRender = document.getElementById( "canRend" );
        ctx = canvas.getContext("2d");
        var imageObj = new Image(); //Canvas image Obj

        imageObj.onload = function() {
            ctx.drawImage(imageObj, 69, 50);    //Load Image on canvas
            renderAllCanvas();
        };
        imageObj.src = 'http://www.html5canvastutorials.com/demos/assets/darth-vader.jpg'; //Load Image 

        w = canvas.width;   // Canvas Width
        h = canvas.height;  // Canvas Height
        //Check Shape to be draw
        eventListener();
    }
    function eventListener(){
        if(currShape=='rectangle'){
            cnvRender.addEventListener("mousedown",function (e) { 
                mouseDown(e);
                renderAllCanvas();
            }, false);
            cnvRender.addEventListener("mousemove",function (e){
                mouseXY(e);
                renderAllCanvas();
            }, false);
            cnvRender.addEventListener("mouseup", function (e){ 
                mouseUp(e);
                renderAllCanvas();
            }, false);
        }
    }
    function mouseUp(eve) {
    if (mouseIsDown !== 0) {
        mouseIsDown = 0;
        var pos = getMousePos(canvas, eve);
        endX = pos.x;
        endY = pos.y;
        if(currShape=='rectangle')
        {
            drawSquare( canvas ); //update on mouse-up
            cnvHid.getContext( "2d" ).clearRect( 0, 0, cnvHid.width, cnvHid.height );
        }
    }
}

function mouseDown(eve) {
    mouseIsDown = 1;
    var pos = getMousePos(canvas, eve);
    startX = endX = pos.x;
    startY = endY = pos.y;
    if(currShape=='rectangle')
    {
        drawSquare( canvas ); //update on mouse-up
    }
}

function mouseXY(eve) {
    if (mouseIsDown !== 0) {
        var pos = getMousePos(canvas, eve);
        endX = pos.x;
        endY = pos.y;
        drawSquare( cnvHid, true );
    }
}

function drawSquare( cnv, clear ) {
    var ctx = cnv.getContext( "2d" );
    if( clear && clear === true ){
        ctx.clearRect( 0, 0, cnv.width, cnv.height );
    }
    // creating a square
    var w = endX - startX;
    var h = endY - startY;
    var offsetX = (w < 0) ? w : 0;
    var offsetY = (h < 0) ? h : 0;
    var width = Math.abs(w);
    var height = Math.abs(h);

    ctx.beginPath();
    ctx.globalAlpha=0.7;
    ctx.rect(startX + offsetX, startY + offsetY, width, height);
    ctx.fillStyle = x;
    ctx.fill();
    ctx.lineWidth = y;
    ctx.strokeStyle = x;
    ctx.stroke();
    ctx.closePath();
}

function getMousePos(canvas, evt) {
    var rect = canvas.getBoundingClientRect();
    return {
        x: evt.clientX - rect.left,
        y: evt.clientY - rect.top
    };
}

function renderAllCanvas(){
    var cnxRender = cnvRender.getContext( "2d" );
    cnxRender.drawImage(
        canvas
        ,0,0
        ,cnvRender.width,cnvRender.height
    );
    cnxRender.drawImage(
        cnvHid
        ,0,0
        ,cnvRender.width,cnvRender.height
    );
}

这是你的新HTML

<!DOCTYPE HTML>
<html>
    <body onload="init()">
        <div class="canvasbody">
        <canvas id="can" width="400" height="400" style="display: none;"></canvas>
        <canvas id="canHid" width="400" height="400" style="display: none;"></canvas>
        <canvas id="canRend" width="400" height="400" style="border:1px dotted #eee;"></canvas>
        </div>
    </body>
</html>

答案 3 :(得分:0)

您当前的代码在鼠标移动时注释了重绘,这是更新画布所必需的。但是,您的代码也会像绘制矩形一样破坏图像。如果您保留如下所示的图像并在绘制矩形之前在每个帧上重绘它,它可能会产生所需的效果。

var canvas, ctx, flag = false,
        prevX = 0,
        currX = 0,
        prevY = 0,
        currY = 0,
        currShape = 'rectangle',
        mouseIsDown = 0,
        startX, endX, startY, endY,
        dot_flag = false;
        var x = "white",
        y = 2, 
        image = null;

   
    function init() {
        canvas = document.getElementById('can');
        ctx = canvas.getContext("2d");
        var imageObj = new Image(); //Canvas image Obj

        imageObj.onload = function() {
            image = imageObj;
            ctx.drawImage(image, 69, 50);    //Load Image on canvas
        };
        imageObj.src = 'http://www.html5canvastutorials.com/demos/assets/darth-vader.jpg'; //Load Image 

        w = canvas.width;   // Canvas Width
        h = canvas.height;  // Canvas Height
        //Check Shape to be draw
        eventListener();

    }
    function eventListener(){
        if(currShape=='rectangle'){
            canvas.addEventListener("mousedown",function (e) { 
                mouseDown(e);
            }, false);
            canvas.addEventListener("mousemove",function (e){
                mouseXY(e);
            }, false);
            canvas.addEventListener("mouseup", function (e){ 
                mouseUp(e);
            }, false);
        }
    }

function mouseUp(eve) {
    if (mouseIsDown !== 0) {
        mouseIsDown = 0;
        var pos = getMousePos(canvas, eve);
        endX = pos.x;
        endY = pos.y;
        if(currShape=='rectangle')
        {
            drawSquare(); //update on mouse-up
        }
    }
}

function mouseDown(eve) {
    mouseIsDown = 1;
    var pos = getMousePos(canvas, eve);
    startX = endX = pos.x;
    startY = endY = pos.y;
    if(currShape=='rectangle')
    {
        drawSquare(); //update on mouse-up
    }
}

function mouseXY(eve) {
    if (mouseIsDown !== 0) {
        var pos = getMousePos(canvas, eve);
        endX = pos.x;
        endY = pos.y;
        drawSquare();
    }
}

function drawSquare() {

    // draw background image
    if(image) {
        ctx.drawImage(image, 69, 50);
    }

    // creating a square
    var w = endX - startX;
    var h = endY - startY;
    var offsetX = (w < 0) ? w : 0;
    var offsetY = (h < 0) ? h : 0;
    var width = Math.abs(w);
    var height = Math.abs(h);
              
    ctx.beginPath();
    ctx.globalAlpha=0.7;
    ctx.rect(startX + offsetX, startY + offsetY, width, height);
    ctx.fillStyle = x;
    ctx.fill();
    ctx.lineWidth = y;
    ctx.strokeStyle = x;
    ctx.stroke();
}

function getMousePos(canvas, evt) {
    var rect = canvas.getBoundingClientRect();
    return {
        x: evt.clientX - rect.left,
        y: evt.clientY - rect.top
    };
}
.colortool div {
        width: 15px;
        height: 15px;
        float: left;
        margin-left: 2px;
    }
    .clear {
      clear: both;
    }
<!DOCTYPE HTML>
<html>
    <body onload="init()">
     <div class="canvasbody">
     <canvas id="can" width="400" height="400" style="border:1px dotted #eee;"></canvas>
     </div>
    </body>
    </html>