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

External CSS does not load in web page

css spring spring-mvc

I am developing a web application using Spring and Tomcat 7.0. When I test the page in a browser it does not apply the CSS because it is unable to load the external stylesheet.

How to use the data from the row selected?

javascript event-handling event-delegation

How can I collect the data on the row from the table that I select and use it in the result?