Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

select a drawn object in canvas

I have a drawn image in canvas with context.drawImage() and I want to select that image to move it with drag and drop in the same canvas (same as MS Paint selection tool). How can I code that in javascript?

function crop(xStart,yStart,xLast,yLast){
    canvas.width = xLast - xStart;
    canvas.height = yLast - yStart;
    context.clearRect(0, 0, canvas.width,canvas.height);           drawFromAux(xStart,yStart,xLast,yLast,0,0);
    return canvas.toDataURL();
}
// img is my original image
function select(xStart,yStart,xLast,yLast){

    selection.src = crop(xStart,yStart,xLast,yLast);
    selection.draggable = "true";
    
    context.clearRect(0, 0, canvas.width,canvas.height);                
    canvas.width = img.width;
    canvas.height = img.height;
    context.clearRect(0, 0, canvas.width,canvas.height);                
    context.drawImage(img, 0, 0);
    context.clearRect(xStart, yStart, xLast - xStart,yLast - yStart); 
    context.drawImage(selection,0,0); 

}
like image 654
Aria Avatar asked Nov 26 '25 05:11

Aria


1 Answers

Using Canvas.js and Pointer.js that should not be that hard.

Things to do:

  1. create image object containing with x, y and raw image
  2. render it to a canvas
  3. listen for mouse moves and check if mouse button is pressed
  4. simple point collision detection between mouse and image on canvas to be able to "select it" and drag it

Loading Pointer.js and Canvas.js:

<script type="text/javascript" src="https://gustavgenberg.github.io/handy-front-end/Canvas.js"></script>
<script type="text/javascript" src="https://gustavgenberg.github.io/handy-front-end/Pointer.js"></script>

1) Creating an image object is not very hard:

const image = {
    image: new Image(),
    x: canvas.width / 2 - image.width / 2, // centered in canvas
    y: canvas.height / 2 - image.height / 2 // centered in canvas
};

image.image.src = ' <url> ';

2) Render that image to the canvas (using Canvas.js)

const canvas = new Canvas('my-canvas', 500, 500).start();

canvas.on('draw', function ( renderer ) {
    renderer.drawImage(image.image, image.x, image.y);
});

3) Listening for mouse moves and moving the image (using Pointer.js)

const pointer = new Pointer( canvas.element );

let moveImage = false;

pointer.on('move', function ( event ) {
    if( moveImage ) {
        image.x += (event.x - pointer.getMoveHistory(-2).x);
        image.y += (event.y - pointer.getMoveHistory(-2).y);
    }
});

4) Pointer collision detection (using Pointer.js)

pointer.on('down', function () {

    moveImage = pointer.touches({ x: image.x, y: image.y, width: image.image.width, height: image.image.height });

});

pointer.on('up', function () {

    moveImage = false;

});

JSFiddle: https://jsfiddle.net/GustavGenberg/3h39b9h1/

Hope this helps you :) !

like image 197
Gustav G Avatar answered Nov 28 '25 18:11

Gustav G