使用jQuery繪製DIV的背景圖像到HTML畫布
你可以得到一個下降div的背景圖片的URL是這樣的:
var img = ui.draggable;
var bkURL=img.css("background-image");
bkURL=bkURL.substr(5).substr(0,bkURL.length-7);
然後你只需新建一個圖像元素,並將該網址作爲其.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>
那真的是你救了我大量的時間有很大的答案 – Sora