How to drag an image within canvas as well as draw on the same canvas ?

Discussion in 'JavaScript' started by zed420, Feb 16, 2017.

  1. #1
    Hi All,
    Here I'm trying to draw on a html5 canvas as well as upload some images and drag them within the same canvas. The problem is I can not drag every uploaded image, at the moment I can only drag the last one rest become part of background image. I know I need to instantiate each image but It doesn't seem to work. Can anyone point me to right direction please.

    <canvas id="can" class="can" width="600" height="400"></canvas>
    <input type="file" id="imageLoader" class="imageLoader" name="imageLoader"/> &nbsp;
    <img id="drag" class="drag" alt="image" src="" draggable="true">
    HTML:
    <script>
               var canvas, ctx, message = "", img, imageLoader, prevX = 10, currX = 10, prevY = 10, currY = 10,
                        dot_flag = false, flag = false, x = "black", y = 2, canvasLeft, canvasTop, imgData, data,
                        startOffsetX = 0, startOffsetY = 0;
             
                function init() {
                    canvas = document.getElementById('can');
                    ctx = canvas.getContext("2d");
                    w = canvas.width;
                    h = canvas.height;
                    img = document.getElementById("drag");
    
                    canvas.addEventListener("mousemove", function (e) { findxy('move', e) }, false);
                    canvas.addEventListener("mousedown", function (e) { findxy('down', e) }, false);
                    canvas.addEventListener("mouseup", function (e) { findxy('up', e) }, false);
                    canvas.addEventListener("mouseout", function (e) {   findxy('out', e) }, false);
    
                    imageLoader = document.getElementById('imageLoader');
                    imageLoader.addEventListener('change', handleImage, false);
    
                    var contexts = [];
                    contexts.push(canvas.getContext('2d'));
    
                    function clearAll() {
                        ctx.clearRect(0, 0, canvas.width, canvas.height);
                    }
    
                    canvas.onclick = function (e) {
                        handleClick(e, 1);
                    };
    
                    function handleClick(e, contextIndex) {
                        e.stopPropagation();
                        var mouseX = parseInt(e.clientX - e.target.offsetLeft);
                        var mouseY = parseInt(e.clientY - e.target.offsetTop);
    
                        for (var i = 0; i < states.length; i++) {
    
                            var state = states[i];
                            if (state.dragging) {
                                state.dragging = false;
                                state.draw();
                                continue;
                            }
                            if (state.contextIndex === contextIndex
                                    && mouseX > state.x && mouseX < state.x + state.width
                                    && mouseY > state.y && mouseY < state.y + state.height)
                            {
                                state.dragging = true;
                                state.offsetX = mouseX - state.x;
                                state.offsetY = mouseY - state.y;
                                state.contextIndex = contextIndex;
                            }
                            state.draw();
                        }
                    }
                    canvas.onmousemove = function (e) {
                        handleMousemove(e, 1);
                    }
    
                    function handleMousemove(e, contextIndex) {
                        e.stopPropagation();
    
                        var mouseX = parseInt(e.clientX - e.target.offsetLeft);
                        var mouseY = parseInt(e.clientY - e.target.offsetTop);
                        for (var i = 0; i < states.length; i++) {
    
                            var state = states[i];
                            if (state.dragging) {
                                state.x = mouseX - state.offsetX;
                                state.y = mouseY - state.offsetY;
                                state.contextIndex = contextIndex;
                            }
                            state.draw();
                        }
                    }
                    var states = [];
                    states.push(addState(0, 0, img));
    
                    function addState(x, y, image) {
                        state = {}
                        state.dragging = false;
                        state.contextIndex = 1;
                        state.image = image;
                        state.x = x;
                        state.y = y;
                        state.width = image.width;
                        state.height = image.height;
                        state.offsetX = 0;
                        state.offsetY = 0;
                        state.draw = function () {
             
                        if (this.dragging) {
                                restore();
                            }
                        ctx.drawImage(this.image, this.x, this.y);
                        };
                            state.draw();
                            return(state);
                        }
    
                }//end of init()
    
                var imgArray = [];
                function handleImage(e) {
                    var reader = new FileReader();
                    reader.onload = function (event) {
                        imgArray.push(img);
                        for (i = 0; i < imgArray.length; i++) {
                            img.src = imgArray[i];
                            img.setAtX = i * 50;
                            img.setAtY = i * 0;
                            img.onload = function () {
                                ctx.drawImage(this, this.setAtX, this.setAtY);
                            };
                            img.src = event.target.result;
                        }
                    };
                    reader.readAsDataURL(e.target.files[0]);
                    save();
                }
    
                function findxy(res, e) {
                    if (res === 'down') {
                        prevX = currX;
                        prevY = currY;
                        currX = e.clientX - canvas.offsetLeft;
                        currY = e.clientY - canvas.offsetTop;
    
                        flag = true;
                        dot_flag = true;
                        if (dot_flag) {
                            ctx.beginPath();
                            ctx.fillStyle = x;
                            ctx.fillRect(currX, currY, 2, 2);
                            ctx.closePath();
                            dot_flag = false;
                        }
                    }
                    if (res === 'up' || res === "out") {
                        flag = false;
                    }
                    if (res === 'move') {
                        if (flag) {
                            prevX = currX;
                            prevY = currY;
                            currX = e.clientX - canvas.offsetLeft;
                            currY = e.clientY - canvas.offsetTop;
                            draw();
                        }
                    }
                }
    
                function save() {
                    imgData = ctx.getImageData(0, 0, canvas.width, canvas.height);
                }
    
                function restore() {
                    ctx.putImageData(imgData, 0, 0);
                }
    
                //Draw lines or text
                function draw() {
                    ctx.beginPath();
                    ctx.moveTo(prevX, prevY);
                    ctx.lineTo(currX, currY);
                    ctx.strokeStyle = x;
                    ctx.lineWidth = y;
                    ctx.stroke();
                    ctx.closePath();
                    ctx.fillStyle = x;
                    ctx.font = "Italic Bold 14pt Times, serif";
                    ctx.fillText(message, prevX, prevY);
                    save();
    
                }
        </script>
    Code (JavaScript):

     
    Last edited: Feb 16, 2017
    zed420, Feb 16, 2017 IP