Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Move image inside HTML canvas with mouse dragging

I have one image that I need to resize, move, and rotate inside a Canvas, and than another image that I use as a mask to clip the other image using globalCompositeOperation = "source-in";

Here is a fiddle.

I was thinking about to add buttons to move the image but why not the mouse? However, I can't find a way how to integrate a dragging function in this code. What do I need to change or hadd here?

like image 659
BeoWulf Avatar asked Feb 21 '14 21:02

BeoWulf


1 Answers

Original - move outer image

See this jsfiddle

Code:

$(window).mousemove(function(event) {
  $("#stcanvas").css({"left" : event.pageX, "top" : event.pageY});
});

css:

#stcanvas
{
    position:absolute;    
}

You would obviously add a button to enable movement. Alternatively, you may want to use jquery UI for in-built drag and drop.

Update - move clip

See this jsfiddle.

If what you mean is that you would like to move the clip rather than the image, then do something like this:

$(window).mousemove(function(event) {
    var cWidth = $("#stcanvas").width();    
    moveXAmount = (event.pageX / $(window).width())*cWidth;    
    moveXAmount = moveXAmount - (cWidth/2);
    var cHeight = $("#stcanvas").height(); 
    moveYAmount = (event.pageY / $(window).height())*cHeight;    
    moveYAmount = moveYAmount - (cHeight/2);
    buildcanvas();
});

and in make_pic do this:

ctx.drawImage(mask_image, moveXAmount, moveYAmount);

Update 2 - move clip and inner image

see this fiddle

If you want to move the image and the clip, then , basically you just add the moveXAmount and moveYAmount to drawImage. Hopefully I have exhausted all possibilities now ;)

ctx.drawImage(pic_image, -400 / 2+moveXAmount, -550 / 2+moveYAmount, im_width, im_height);

Update 3 move image and not mask as per comment

See this fiddle

The main change is:

$("#stcanvas").mousedown(function(){
    isDragging = true;
});

$(window).mouseup(function(){
    isDragging = false;
});
like image 120
acarlon Avatar answered Nov 06 '22 01:11

acarlon