Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to drag a canvas with helper 'clone'?

I have a simple HTML canvas

<div class='circle'>
  <canvas id="myCanvas" width="100" height="100">Your browser does not support the HTML5 canvas tag.</canvas>
</div>

with style

.circle {
  height: auto;
  width: auto;
}

and script

var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.beginPath();
ctx.arc(50, 50, 50, 0, 2 * Math.PI);
ctx.fill();

$('.circle').draggable({
    helper: 'clone' // Remove this line to make it draggable
});

It seems that I cannot use the helper option where i want to keep a copy of the circle at the original position when i drag it around. The draggable will work only if i remove the helper option. This only happened to canvas, not if I draw the circle using css. Fiddle is here. Thanks!

like image 344
marsant Avatar asked Sep 26 '13 22:09

marsant


1 Answers

Unfortunately when you clone a canvas element, this doesn't copy over the image data. You may want to instead export your canvas data as a data url and clone the image instead.

Fiddle: http://jsfiddle.net/gwwar/Bdpq9/2/

<div class='circle'>
</div>

var c = document.createElement("canvas");
var ctx = c.getContext("2d");
ctx.beginPath();
ctx.arc(50, 50, 50, 0, 2 * Math.PI);
ctx.fill();
var url = c.toDataURL();
var img = document.createElement("img");
img.setAttribute("src",url);
$(".circle").append(img);

$('.circle').draggable({
    helper: 'clone' // Remove this line to make it draggable
});
like image 106
Kerry Liu Avatar answered Oct 02 '22 17:10

Kerry Liu