$(document).ready(function () {
var d_canvas = document.getElementById('canvas');
var context = d_canvas.getContext('2d');
var background = document.getElementById('background');
var ballon = document.getElementById('ballon')
context.drawImage(background, 0, 0);
$('#ballon').draggable();
});
当我尝试拖动图像时,它不像在Canvas中。不像谷歌地图拖动
答案 0 :(得分:1)
我在回答你之前提出的问题。您应该使用drawImage
在画布上绘制图像,然后在画布上绘制拖动事件的AddEventListener。
var drag, canvas, ctx;
var posX = 0, posY = 0;
var lastX, lastY;
$(document).ready(function(){
canvas=document.getElementById("canvas");
ctx=canvas.getContext("2d");
var image=document.createElement("img");
image.onload=function(){
canvas.width = 800;
canvas.height = 400;
ctx.drawImage(image,posX,posY);
init();
}
image.src="http://peach.blender.org/wp-content/uploads/poster_rodents_big.jpg";
function init(){
canvas.addEventListener('mousedown', function(){
drag = true;
lastX=null;
lastY=null;
});
document.addEventListener('mouseup', function(){
drag = false;
});
document.addEventListener('mousemove', function(evt) {
if(drag){
var mousePos = getMousePos(canvas, evt);
var x = mousePos.x;
var y = mousePos.y;
ctx.clearRect(0,0,canvas.width,canvas.height);
if(lastX && lastY){
posX += x-lastX;
posY += y-lastY;
if(posX>0) posX=0;
if(posY>0) posY=0;
if(posX<-image.width+canvas.width) posX = -image.width+canvas.width;
if(posY<-image.height+canvas.height) posY = -image.height+canvas.height;
ctx.drawImage(image,posX,posY);
}
lastX=x;
lastY=y;
}
}, false);
}
function getMousePos(canvas, evt) {
var rect = canvas.getBoundingClientRect();
return {
x: evt.clientX - rect.left,
y: evt.clientY - rect.top
};
}
});