Introduction
In this article, we will learn how to drag an image in a canvas. Canvas is one of the important tags used to display images or text in an HTML5 application. We know that HTML5 is an advanced version of HTML used to develop multimedia and animated applications. This article is intended to help with the use of HTML5 tools to drag an image in canvas applications. We developed this application with some help from JavaScript; JavaScript was designed to add interactivity to HTML pages. JavaScript is usually embedded directly into HTML pages. I hope this article helps to create an application that drags an image in an HTML 5 canvas and JavaScript tools.
Step 1: Open Visual Studio.
- Go to file -> New->Projects.
- Create an ASP. NET Web Application.
- Name of "Canvas.aspx".


- Right-click on the Solution Explorer.
- Add->add new item->HTML form.
- The Name of the HTML form is "Image.html".


- Right-click on the Solution Explorer.
- Add-> Add New Folder.
- Set the name of the folder as "image".



Code
- var Rxt = document.getElementById('Con1').getContext('2d');
- Rxt.fillStyle = 'green';
- Rxt.fillRect(0, 0, 2000, 2000);
- Rxt.rotate(.2);
Step 5: In this section we create a variable named "Img" that is used to provide an image path and set a drag image of a size.
Code
- var Img = document.createElement('img');
- Img.src = 'image/cd3310.gif';
- Img.onload = function () { Rxt.drawImage(Img, 50, 0, 200, 200); }
- var down = false;
- Rxt.canvas.addEventListener('mousedown', function () { down = true; }, false);
- Rxt.canvas.addEventListener('mouseup', function () { down = false; }, false);
- Rxt.canvas.addEventListener('mousemove', function (event) {
- if (down)
- {
- Rxt.translate(0, -50);
- Rxt.drawImage(Img, event.clientX - this.offsetLeft,
- event.clientY - this.offsetTop, 100, 100);
- Rxt.translate(0, 50);
- }





Join the conversation! Your thoughts help the community grow.