javascripthtmldrag-and-drophtml5-canvas

Drag & drop image on canvas image


I want to drag & drop text above image. For that I am using canvas. I am using this code

var c = document.getElementById("canvas");
var ctx1 = c.getContext("2d");
var img = document.getElementById("scream");
ctx1.drawImage(img, 10, 10);

var canvas;
var ctx;
var x = 75;
var y = 50;
var dx = 5;
var dy = 3;
var WIDTH = 400;
var HEIGHT = 300;
var dragok = false,
  text = "Hey there im moving!",
  textLength = (text.length * 14) / 2;

function rect(x, y, w, h) {
  ctx.font = "14px Arial";
  ctx.strokeText("Hey there im a moving!!", x, y);
}

function clear() {
  ctx.clearRect(0, 0, WIDTH, HEIGHT);
}

function init() {
  canvas = document.getElementById("canvas");
  ctx = canvas.getContext("2d");
  return setInterval(draw, 10);
}

function draw() {
  clear();
  ctx.fillStyle = "#FAF7F8";
  ctx.fillStyle = "#444444";
  rect(x - 15, y + 15, textLength, 30);
}

function myMove(e) {
  if (dragok) {
    x = e.pageX - canvas.offsetLeft;
    y = e.pageY - canvas.offsetTop;
  }
}

function myDown(e) {
  if (e.pageX < x + textLength + canvas.offsetLeft && e.pageX > x - textLength + canvas.offsetLeft && e.pageY < y + 15 + canvas.offsetTop &&
    e.pageY > y - 15 + canvas.offsetTop) {
    x = e.pageX - canvas.offsetLeft;
    y = e.pageY - canvas.offsetTop;
    dragok = true;
    canvas.onmousemove = myMove;
  }
}

function myUp() {
  dragok = false;
  canvas.onmousemove = null;
}

init();
canvas.onmousedown = myDown;
canvas.onmouseup = myUp;
<img id="scream" src="http://127.0.0.1/demo/images.jpg" alt="The Scream" style="display:none;" width="220" height="277">
<p>Canvas:</p>
<canvas id="canvas" width="300" height="300" style="border:1px solid #d3d3d3;">
           Your browser does not support the HTML5 canvas tag.</canvas>

I either able to show image or drag & drop text but I want both, please help me where I am wrong. You can check here:- http://jsfiddle.net/FWdSv/11/


Solution

  • When you're clearing the canvas, you're also clearing your image.

    So the easy fix is to redraw the image in your draw function:

    function draw() {
     clear();
     ctx.drawImage(img,0,0);
     ctx.fillStyle = "#FAF7F8";
     ctx.fillStyle = "#444444";
     rect(x - 15, y + 15, textLength, 30);
    }
    

    Alternatively:

    You could display your image underneath your canvas so it's not affected when you clear the canvas.