Skip to content Skip to sidebar Skip to footer

Drag Image In Html5 Canvas With Defined Boundaries

I am working on HTML5 Canvas 2D, is there any function which can help to do like example given in below link - http://www.html5canvastutorials.com/kineticjs/html5-canvas-drag-and-

Solution 1:

Below is the link and code. http://html5.litten.com/how-to-drag-and-drop-on-an-html5-canvas/

<html><head></head><body><section><div><canvasid="canvas5"height="300"width="400"> This text is displayed if your browser does not support HTML5 Canvas. </canvas></div><scripttype="text/javascript">var canvas5;
    var ctx5;
    var x5 = 75;
    var y5 = 50;
    var dx5 = 5;
    var dy5 = 3;
    varWIDTH5 = 400;
    varHEIGHT5 = 300;
    var dragok = false;
    functionrect(x,y,w,h) {
    ctx5.beginPath();
    ctx5.rect(x,y,w,h);
    ctx5.closePath();
    ctx5.fill();
    }
    functionclear() {
    ctx5.clearRect(0, 0, WIDTH5, HEIGHT5);
    }
    functioninit() {
    canvas5 = document.getElementById("canvas5");
    ctx5 = canvas5.getContext("2d");
    returnsetInterval(draw5, 10);
    }
    functiondraw5() {
if(x5>10 && x5<350 && y5>10 && y5<350)
{
    clear();
    ctx5.fillStyle = "#FAF7F8";
    rect(0,0,WIDTH5,HEIGHT5);
    ctx5.fillStyle = "#444444";
    rect(x5 - 15, y5 - 15, 30, 30);
    }
    }
    functionmyMove(e){
    if (dragok){
    x5 = e.pageX - canvas5.offsetLeft;
    y5 = e.pageY - canvas5.offsetTop;
    }
    }
    functionmyDown(e){
    if (e.pageX < x5 + 15 + canvas5.offsetLeft)
    if (e.pageX > x5 - 15 + canvas5.offsetLeft)
    if (e.pageY < y5 + 15 + canvas5.offsetTop)
    if (e.pageY > y5 -15 + canvas5.offsetTop){
    x5 = e.pageX - canvas5.offsetLeft;
    y5 = e.pageY - canvas5.offsetTop;
    dragok = true;
    canvas5.onmousemove = myMove;
    }
    }
    functionmyUp(){
    dragok = false;
    canvas5.onmousemove = null;
    }
    init();
    canvas5.onmousedown = myDown;
    canvas5.onmouseup = myUp;
    </script></section></body></html>

Solution 2:

If you want a clean tutorial on how to make objects draggable inside an HTML5 Canvas I've written a tutorial with a lot of explanation here.

For every object you create that is painted on the canvas you will probably want to also give it some kind of "limit bounds" such as limitX, limitY, limitWidth, limitHeight, etc. Then while you are dragging you need to make sure it remains within those bounds. If it is out of bounds you just force it to be on the closest side that it was attempted to be dragged out of.

Post a Comment for "Drag Image In Html5 Canvas With Defined Boundaries"