Reputation: 2551
I have this jsfiddle : http://jsfiddle.net/VFZ4m/11/
when the user drop the div the same image should be created and drawn inside the canvas how can I do that ?
i tried this code but it's not functioning
$('#x').draggable();
$('#c').droppable({
drop: function(event, ui) {
var img = ui.draggable;
var ctxt =$("#c")[0].getContext("2d");
ctxt.drawImage(img[0], 0, 0);
return false;
}
});
Upvotes: 0
Views: 2609
Reputation: 105015
Using jQuery to draw a div background-image onto html canvas
You can get a dropped div’s background-image URL like this:
var img = ui.draggable;
var bkURL=img.css("background-image");
bkURL=bkURL.substr(5).substr(0,bkURL.length-7);
Then you just new-up an image element with that URL as its .src:
var img=new Image();
img.onload=function(){
ctxt.drawImage(img, 0, 0);
}
img.src=bkURL
Here is code and a Fiddle: http://jsfiddle.net/m1erickson/WzHvJ/
<!doctype html>
<html lang="en">
<head>
<style>
body {
padding: 20px;
}
#x {
border: 1px solid green;
cursor: move;
background:url('http://www.kidzui.com/images/layout/spaceship/star-orange-full.png') no-repeat;
height:40px;
width:40px;
}
#x, #c {
display: block;
clear: both;
}
#c {
margin-top: 30px;
border: 1px solid red
}
</style>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<script>
$(function() {
$('#x').draggable();
$('#c').droppable({
drop: function(event, ui) {
var img = ui.draggable;
var bkURL=img.css("background-image");
bkURL=bkURL.substr(5).substr(0,bkURL.length-7);
var ctxt =$("#c")[0].getContext("2d");
var img=new Image();
img.onload=function(){
ctxt.drawImage(img, 0, 0);
}
img.src=bkURL
return false;
}
});
}); // end $(function(){});
</script>
</head>
<body>
<div id="x"> </div>
<canvas id="c" width="200" height="200">
</body>
</html>
Upvotes: 1
Reputation: 339816
You can't access an image stored as a CSS background image like that - there is no image element.
It does work if the image is a real <img>
tag within the <div>
See http://jsfiddle.net/alnitak/DuCVG/1/
The (much harder) alternative would be to use window.getComputedStyle()
to read the background-image
CSS property from the element, parse it, and then create a brand new Image
object that has the same source.
Upvotes: 1