How to drag and drop canvas images and click Images

Source: Internet
Author: User

After writing the last canvas blog post, a friend hopes to click, drag, and drop the image drawn by canvas, because the image drawn by canvas can be beautified. It seems that I want to play Firestone or something, and I have never played it.

In my understanding, canvas is like drawing an image on a canvas. It can only be seen but cannot be "touched". How can I operate it. I don't know how to do this on the Internet. Here I use my own ideas to make a demo and share it with you.

Ideas:

Although canvas cannot be dragged, div can be dragged. How can we combine them. The initial idea is to overwrite a div of the same size as the canvas image. When dragging the DIV, correct the obtained cursor coordinates and send them to the canvas to draw a function and refresh the image position.

To overwrite the data, make the following preparations:

1. Set the position: absolute of the Div and canvas; otherwise, the DIV and canvas cannot overlap.

2. Set the Z-index value of the DIV to a greater value to ensure that it is on the canvas screen.

After the preparation is complete, let's look at the drag and drop of the DIV:

    var divObj=document.getElementById("cover");    var moveFlag=false;        divObj.onmousedown=function(e){        moveFlag=true;        var clickEvent=window.event||e;        var mwidth=clickEvent.clientX-divObj.offsetLeft;        var mheight=clickEvent.clientY-divObj.offsetTop;        document.onmousemove=function(e){            var moveEvent=window.event||e;            if(moveFlag){                divObj.style.left=moveEvent.clientX-mwidth+"px";                divObj.style.top=moveEvent.clientY-mheight+"px";                divObj.onmouseup=function(){                    moveFlag=false;                }            }        }    };

Get the DIV object and set the drag icon moveflage. If onmousedown is set to true, you can drag the object. If onmouseup is set to false, you cannot drag the object.

      var clickEvent=window.event||e;      var mwidth=clickEvent.clientX-divObj.offsetLeft;      var mheight=clickEvent.clientY-divObj.offsetTop;

These three lines of code are used to modify the cursor position. When you click, record the cursor position on the div. Mwidth and mheight indicate the distance between the cursor position and the left and top of the div. If no correction is added:

This is the result without correction. When the coordinate point is under the optical coordinate point, the coordinates of the DIV, that is, the upper left corner, will be consistent with the coordinates of the cursor.

After correction:

Clicking the time Mark always sticks to a certain point in the div.

Next, draw the image:

First, define global variables X and Y to update the drawing coordinates of the image in real time.

 var ctx=document.getElementById("myCanvas").getContext("2d"); var img=document.getElementById("myImg");    function drawImg(){        ctx.clearRect(0,0,1000,500);        ctx.beginPath();        ctx.drawImage(img,X,Y);        ctx.closePath();        ctx.stroke();    }    window.onload=function(){        setInterval(drawImg,1);    }

Get the "paint brush" to get the image object. Here, setinterval cyclically executes the image rendering function to refresh the image position. The smaller the interval value of setinterval, the smoother the drag operation ".

Do not forget clearrect. When the image is moved to the next position, clear the image at the previous position. The parameter is the coordinates and size of the canvas.

When dragging, the corrected cursor coordinates are transmitted to X and Y:

 X=moveEvent.clientX-mwidth; Y=moveEvent.clientY-mheight;

Finally, add the DIV and the activity range of the image:

if(moveEvent.clientX<=mwidth){        divObj.style.left=0+"px";        X=0;}if(parseInt(divObj.style.left)+divObj.offsetWidth >=1000){        divObj.style.left=1000 - divObj.offsetWidth+"px";        X=1000 - divObj.offsetWidth;}if(moveEvent.clientY<=mheight){        divObj.style.top=0+"px";        Y=0;}if(parseInt(divObj.style.top)+divObj.offsetHeight>=500){       divObj.style.top=500-divObj.offsetHeight+"px";       Y=500-divObj.offsetHeight;}

This depends on the individual's requirements. Note that the range of Div and image activity must be limited at the same time. The size of the canvas in this example is 1000 and 500. If the canvas is active throughout the page, it is changed to innerwidth or innerheight.

Hide the DIV to see the effect:

Finally, let's talk about the click event. Here we should note that onmousedown and onmouseup constitute a click process during the drag and drop process, but we do not want to trigger the click event after the drag and drop.

Here is a simple method to define a clickflag to be set to false by default, set to true when onmousedown, and set to false when onmousemove is performed.

The click event is triggered only when the value of clickflag is determined during onmouseup. That is to say, when you press the mouse, the click event will be triggered only when you do not find any movement.

 

The compiled JS Code:

// Draw the image coordinate var x = 0; var y = 0; // JS part var divobj = document. getelementbyid ("cover"); var moveflag = false; // differences between moueseup and click. var clickflag = false; // drag the divobj function. onmousedown = function (e) {moveflag = true; clickflag = true; var clickevent = Window. event | E; var mwidth = clickevent. clientX-divObj.offsetLeft; var mheight = clickevent. clientY-divObj.offsetTop; document. onmousemove = function (e) {clickflag = false; var moveevent = Window. event | E; If (moveflag) {divobj. style. left = moveevent. clientx-mwidth + "PX"; divobj. style. top = moveevent. clienty-mheight + "PX"; // pass the coordinates of the mouse to the image x = moveevent in the canvas. clientx-mwidth; y = moveevent. clienty-mheight; // the following four conditions limit the DIV and the motion boundary of the image if (moveevent. clientx <= mwidth) {divobj. style. left = 0 + "PX"; X = 0;} If (parseint (divobj. style. left) + divobj. offsetwidth> = 1000) {divobj. style. left = 1000-divobj. offsetwidth + "PX"; X = 1000-divobj. offsetwidth;} If (moveevent. clienty <= mheight) {divobj. style. top = 0 + "PX"; y = 0;} If (parseint (divobj. style. top) + divobj. offsetheight> = 500) {divobj. style. top = 500-divobj.offsetheight + "PX"; y = 500-divobj.offsetheight;} divobj. onmouseup = function () {moveflag = false; If (clickflag) {alert ("click to take effect ");}}}}};

This example ends now. You can develop more functions by yourself. Thank you for your browsing and comments to me.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.