I have different images in svg and png and I want to be able to drag those figures only by their image itself. So I want to be able to "ignore" or disable areas from draggable that are invisible.
I've tried different approaches like drawing the images onto a <canvas> element and tried to get the pixels that are greater than zero but I haven't been successfully. What else could I do?
window.onload = function() {
var c = document.getElementById("canvas");
var ctx = c.getContext("2d");
var img1 = new Image();
img1.src = "favicon.svg";
ctx.drawImage(img1, 0, 0, 200, 150);
$(c).draggable();
var currentCanvas = ctx.getImageData(0, 0, 200, 150);
var pix = currentCanvas.data;
if (pix[3] > 0) { // 0 is transparent, 1 up to 255 is visible
$(pix).draggable();
}
}
Consider the following.
$(function() {
var c = $("#myCanvas");
var ctx = c.get(0).getContext("2d");
ctx.moveTo(0, 0);
ctx.lineTo(100, 100);
ctx.stroke();
c.draggable();
var s = $("#mySVG");
$("circle", s).draggable();
})
#myCanvas {
border: 1px solid #000000;
}
#mySVG circle {
fill: rgb(255, 255, 0);
stroke-width: 1;
stroke: rgb(0, 0, 0)
}
<link rel="stylesheet" href="//code.jquery.com/ui/1.13.2/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-3.6.0.js"></script>
<script src="https://code.jquery.com/ui/1.13.2/jquery-ui.js"></script>
<canvas id="myCanvas" width="100" height="100"></canvas>
<svg width="100" height="100" id="mySVG">
<circle cx="50" cy="50" r="40" />
</svg>
Draggable is applied to both. In the case of the SVG, the circle element is targeted and it is draggable, within it's parent. If you drag it outside the bounds of the SVG, it's no longer in the viewport.
You might be able to use handles option.
$(function() {
$("#mySVG").draggable({
handle: "circle"
});
})
#mySVG circle {
fill: rgb(255, 255, 0);
stroke-width: 1;
stroke: rgb(0, 0, 0)
}
<link rel="stylesheet" href="//code.jquery.com/ui/1.13.2/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-3.6.0.js"></script>
<script src="https://code.jquery.com/ui/1.13.2/jquery-ui.js"></script>
<svg width="100" height="100" id="mySVG">
<circle cx="50" cy="50" r="40" />
</svg>
This way, the whole SVG is draggable, yet will only move when the User targets the Handle.
You can also try to only accept Drag when the proper element is clicked upon in the canvas.
This is discussed more here: Find out which object was clicked on a html5 Canvas
Trying to use the Pixel data might be too difficult. In your example, pix is an array of each pixel. They do not have any positioning reference.