How to Make 8 Images drawn on HTML5 Canvas Draggable with JavaScript

I’m just learn about JavaScript, and I just found how to make draggable image drawn on HTML5 Canvas but It only one image.

So, I want to make 8 images drawn on HTML5 Canvas draggable, here’s my progress :

var canvas = document.getElementById('canvas');
context = canvas.getContext('2d');
var canvasOffset=$("#canvas").offset();
var offsetX=canvasOffset.left;
var offsetY=canvasOffset.top;
var canvasWidth=canvas.width;
var canvasHeight=canvas.height;
var isDragging=false;


$(function(){
var image1 = document.getElementById('btn');

image1.addEventListener('change', handleImage, false);

function handleImage(e){
    var reader = new FileReader();

    reader.onload = function(event){
        var img = new Image();

        img.onload = function(){
            context.drawImage(img,0,0,440,300);
        }   
        img.src = event.target.result;

        function handleMouseDown(e){
            canMouseX=parseInt(e.clientX-offsetX);
            canMouseY=parseInt(e.clientY-offsetY);
            // set the drag flag
            isDragging=true;
        }

        function handleMouseUp(e){
            canMouseX=parseInt(e.clientX-offsetX);
            canMouseY=parseInt(e.clientY-offsetY);
            // clear the drag flag
            isDragging=false;
        }

        function handleMouseOut(e){
            canMouseX=parseInt(e.clientX-offsetX);
            canMouseY=parseInt(e.clientY-offsetY);
            // user has left the canvas, so clear the drag flag
            //isDragging=false;
        }

        function handleMouseMove(e){
            canMouseX=parseInt(e.clientX-offsetX);
            canMouseY=parseInt(e.clientY-offsetY);
            // if the drag flag is set, clear the canvas and draw the image
            if(isDragging){
                context.clearRect(0,0,canvasWidth,canvasHeight);
                context.drawImage(img,canMouseX-128/2,canMouseY-120/2,440,300);
            }
        }

        $("#canvas").mousedown(function(e){handleMouseDown(e);});
        $("#canvas").mousemove(function(e){handleMouseMove(e);});
        $("#canvas").mouseup(function(e){handleMouseUp(e);});
        $("#canvas").mouseout(function(e){handleMouseOut(e);});

        }                       

        reader.readAsDataURL(e.target.files[0]);     
    }
});

This codes only able for one image, I want to put 8 images in one canvas, any solution? please help me…Thank you


Source: html5

Leave a Reply