Draggable image not coming inside the canvas

Fiddle
$(document).ready(function () {
        var d_canvas = document.getElementById('canvas');
        var context = d_canvas.getContext('2d');
        var background = document.getElementById('background');
        var ballon = document.getElementById('ballon')
        context.drawImage(background, 0, 0);

        $('#ballon').draggable();
    });

When i try to drag the image, it is not like inside Canvas. not behaving like Google map dragging

Answers


I was answering your previous question. You should draw image on canvas using drawImage and then addEventListener of drag event on canvas.

jsfiddle

var drag, canvas, ctx;
var posX = 0, posY = 0;
var lastX, lastY;
$(document).ready(function(){
    canvas=document.getElementById("canvas");
    ctx=canvas.getContext("2d");
    var image=document.createElement("img");
    image.onload=function(){
        canvas.width = 800;
        canvas.height = 400;
        ctx.drawImage(image,posX,posY);
        init();
    }

    image.src="http://peach.blender.org/wp-content/uploads/poster_rodents_big.jpg";

    function init(){
        canvas.addEventListener('mousedown', function(){
            drag = true;
            lastX=null;
            lastY=null;
        });

        document.addEventListener('mouseup', function(){
            drag = false;
        });

        document.addEventListener('mousemove', function(evt) {
            if(drag){
                var mousePos = getMousePos(canvas, evt);
                var x = mousePos.x;
                var y = mousePos.y;
                ctx.clearRect(0,0,canvas.width,canvas.height);
                if(lastX && lastY){
                    posX += x-lastX;
                    posY += y-lastY;
                    if(posX>0) posX=0;
                    if(posY>0) posY=0;
                    if(posX<-image.width+canvas.width) posX = -image.width+canvas.width;
                    if(posY<-image.height+canvas.height) posY = -image.height+canvas.height;
                    ctx.drawImage(image,posX,posY);
                }
                lastX=x;
                lastY=y;
            }
        }, false);
    }

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

Need Your Help

Before deleting an entity, deleting its parent reference(s), if any

hibernate jpa eclipselink jpa-2.1

It is essential to delete an entity from its parent list and the parent from the entity itself before the entity is deleted.

Using becomeFirstResponder causes cancel button to not work

ios uisearchbar uisearchdisplaycontroller becomefirstresponder

I have a UISearchDisplayController (searchDisplayCtr) and a UISearchBar (searchBar). I am trying to give focus to the search bar and bring up the keyboard when I click the search icon in the alphabet