var img1 = new Image();
var img2 = new Image();
var img3 = new Image();
var img4 = new Image();
var imageCount = 0, NUM_IMAGES=4;
var ctx;
var WIDTH;
var HEIGHT;
//drag
var draggable = false;
var startX;
var startY;
//array of images
var images=[];
images.push({image:img1, x:0, y:20, width:550, height:466});
images.push({image:img2, x:476, y:170, width:230, height:240});
images.push({image:img3, x:500, y:20, width:635, height:313});
images.push({image:img4, x:910, y:328, width:219, height:134});
function init(){
ctx = $('#myCanvas')[0].getContext("2d");
WIDTH = $("#myCanvas").width();
HEIGHT = $("#myCanvas").height();
ctx.fillStyle = "#A0DCE5";
ctx.fillRect(0,0,WIDTH,HEIGHT);
loadResources();
$('#myCanvas').mousedown(onMouseDown);
$('#myCanvas').mouseup(onMouseUp);
$('#myCanvas').mousemove(onMouseMove);
}
function startInteraction() {
imageCount++;
if (imageCount ==NUM_IMAGES)
render();
}
function loadResources() {
img1.onload = startInteraction;
img1.src = "america.png";
img2.onload = startInteraction;
img2.src = "africa.png";
img3.onload = startInteraction;
img3.src = "europe and asia.png";
img4.onload = startInteraction;
img4.src = "australia.png";
}
function image(image,x,y,width,height) {
ctx.drawImage(image,x,y,width,height)
}
function render() {
for(var i=0;i<images.length;i++){
var r=images[i];
image(r.image,r.x,r.y,r.width,r.height);
}
}
function onMouseDown(e){
// tell browser we're handling this mouse event
e.preventDefault();
e.stopPropagation();
//get current position
var mx=parseInt(e.clientX-$('#myCanvas').offset().left);
var my=parseInt(e.clientY-$('#myCanvas').offset().top);
//test to see if mouse is in image
d = false;
for(var i=0;i<images.length;i++){
var r=images[i];
if(mx>r.x && mx<r.x+r.width && my>r.y && my<r.y+r.height){
//if true set is dragging=true
draggable=true;
}
}
//save mouse position
startX=mx;
startY=my;
}
function onMouseUp(e){
//tell browser we're handling this mouse event
e.preventDefault();
e.stopPropagation();
draggable = false;
for(var i=0;i<images.length;i++){
images[i].isDragging=false;
}
}
function onMouseMove(e){
//if we can drag an image
if(draggable){
//tell brower we're handling this mouse event
e.preventDefault
e.stopPropagation
//get current mouseposition
var mx = parseInt(e.clientX-$('#myCanvas').offset().left);
var my = parseInt(e.clientY-$('#myCanvas').offset().top);
//calculate how far the mouse has moved;
var dx = mx - startX;
var dy = my - startY;
//move each image by how far the mouse moved
for(var i=0;i<images.length;i++){
var r=images[i];
if(r.isDragging){
r.x+=dx;
r.y+=dy;
}
}
//re render the images
render();
//reset the mouse positions for next mouse move;
startX = mx;
startY = my;
}
}
$(document).ready(init);
I am having real difficulty trying to get images to move and every tutorial i look at I just can seem to understand it.
Is there something blindingly obvious I'm doing wrong?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…