使用 jQuery 在 html 画布上绘制一个 div 背景图像
您可以像这样获取已删除的 div 的背景图像 URL:
var img = ui.draggable;
var bkURL=img.css("background-image");
bkURL=bkURL.substr(5).substr(0,bkURL.length-7);
然后,您只需使用该 URL 作为其 .src 来新建一个图像元素:
var img=new Image();
img.onload=function(){
ctxt.drawImage(img, 0, 0);
}
img.src=bkURL
这是代码和小提琴: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>