2015-01-19 2 views
0

Привет всем Я просто пытаюсь понимает, как это делает его работу У меня есть основной холст базы только в JavaScript, и я хотел бы, чтобы переместить его с помощью сенсорного событияКак перенести объект в холст с помощью события касания?

Я не уверен в этом, но Могу ли я используйте событие перетаскивания?

Нужно ли использовать функцию цикла?

Как я могу запустить этот синий куб?

Я знаю, что есть много JavaScript двигателя на самом деле я использую фазер, но я хотел бы undertand это

Спасибо

var canvas, cx, width, height; 
 

 
var cube = { 
 
    x: 80, 
 
    y: 100, 
 
    update: function() { 
 

 
    }, 
 
    draw: function (ctx) { 
 
     ctx.save(); 
 

 
     ctx.fillStyle = "blue"; 
 
     ctx.fillRect(100, 410, 50, 50); 
 

 
     ctx.restore(); 
 
    } 
 
}; 
 

 

 
function onpress(e) { 
 
    e.preventDefault(); 
 
    var whichArt = e.target; 
 
    var touch = e.touches[0]; 
 

 
    var moveOffsetX = whichArt.offsetLeft - touch.pageX; 
 
    var moveOffsetY = whichArt.offsetTop - touch.pageY; 
 

 
    whichArt.addEventListener('touchmove', function() { 
 
     var positionX = touch.pageX + moveOffsetX; 
 
     var positionY = touch.pageY + moveOffsetY; 
 

 
     cube.x = positionX; 
 
     cube.y = positionY; 
 

 
     console.log(cube.x); 
 
    }, false); 
 
} 
 

 
function main() { 
 
    canvas = document.createElement("canvas"); 
 

 
    width = window.innerWidth; 
 
    height = window.innerHeight; 
 

 
    if (width >= 500) { 
 
     width = 320; 
 
     height = 480; 
 
     canvas.style.border = "1px solid #000"; 
 
    } 
 

 
    document.addEventListener("touchstart", onpress); 
 
    canvas.width = width; 
 
    canvas.height = height; 
 
    ctx = canvas.getContext("2d"); 
 
    document.body.appendChild(canvas); 
 
    run(); 
 
} 
 

 

 
function run() { 
 
    var loop = function() { 
 
     update(); 
 
     render(); 
 
     window.requestAnimationFrame(loop, canvas); 
 
    } 
 
    window.requestAnimationFrame(loop, canvas); 
 
} 
 

 
function update() { 
 

 
} 
 

 
function render() { 
 

 
    cube.draw(ctx); 
 
} 
 

 
main();

http://jsfiddle.net/marcogomesr/sxbo3r83/

+0

Там нет 'drag' событий в JS. –

+0

Посмотрите на это -> https://developer.mozilla.org/en-US/docs/Web/Events/dragstart –

+0

Вот информация о том, какие браузеры поддерживают это. http://caniuse.com/#feat=dragndrop Кроме того, это не поможет вам в холсте, так как вы перетаскиваете весь элемент холста. –

ответ

1

Холст - это только пассивная поверхность рисования: вы должны справиться с перетаскиванием самостоятельно.
Ниже приводится короткий пример:
9 Объект draggables должен реализовать isPointInside и быть добавлен в список объекта draggables.
Я использовал объект dragData, который хранит список объектов draggables, объекта, который перетаскивается в данный момент, возможно, вы захотите сохранить начальную/текущую точку перетаскивания и обработать смещение перетаскивания, чтобы пользователь удерживал объект прямо на момент, когда он начал тащиться.

http://jsfiddle.net/3ksvn4y0/3/

var canvas, cx, width, height; 
var canvasRect; 

var cube1, cube2; 

var dragData = { 
    draggables: [], 
    start: {  x: 0,  y: 0 
    }, 
    current: {  x: 0,  y: 0 
    }, 
    target: null 
}; 

function Cube(x,y,w,h, color) { 
    this.x=x; this.y=y; this.w=w; this.h = h; 
    this.color = color; 
} 

Cube.prototype = { 
    update: function() { 

    }, 
    draw: function (ctx) { 
     ctx.fillStyle = this.color; 
     ctx.fillRect(this.x, this.y, this.w, this.h); 
    }, 
    isPointInside: function (x, y) { 
     return (x >= this.x) && (x < this.x + this.w) && (y > this.y) && (y < this.y + this.h); 
    } 
}; 

var pointerCoords = { 
    x: 0, 
    y: 0, 
    update: function (e) { 
     var coords = e.touches ? e.touches[0] : e; 
     this.x = coords.pageX - canvasRect.left; 
     this.y = coords.pageY - canvasRect.top; 
    } 
}; 


function onStart(e) { 
    e.preventDefault(); 
    pointerCoords.update(e); 
    // look if we start the touch within a draggable object 
    var target = null; 
    for (var i = 0; i < dragData.draggables.length; i++) { 
     var draggable = dragData.draggables[i]; 
     if (draggable.isPointInside(pointerCoords.x, pointerCoords.y)) { 
      target = draggable; 
      break; 
     } 
    } 
    dragData.target = target; 
} 

function onMove(e) { 
    pointerCoords.update(e); 
    var target = dragData.target; 
    if (!target) return; 
    target.x = pointerCoords.x; 
    target.y = pointerCoords.y; 
} 

function onStop(e) { 
    pointerCoords.update(e); 
    e.preventDefault(); 
    if (!dragData.target) return; 
    onMove(e); 
    dragData.target = null; 
} 

function main() { 
    canvas = document.createElement("canvas"); 

    width = window.innerWidth; 
    height = window.innerHeight; 

    if (width >= 500) { 
     width = 320; 
     height = 480; 
     canvas.style.border = "1px solid #000"; 
    } 

    canvas.width = width; 
    canvas.height = height; 
    ctx = canvas.getContext("2d"); 
    document.body.appendChild(canvas); 
    canvasRect = canvas.getBoundingClientRect(); 
    canvas.addEventListener("touchstart", onStart); 
    canvas.addEventListener('touchmove', onMove); 
    canvas.addEventListener("touchstop", onStop); 
    canvas.addEventListener("mousedown", onStart); 
    canvas.addEventListener('mousemove', onMove); 
    canvas.addEventListener("mouseup", onStop); 

    cube1 = new Cube(100, 80, 30, 30, 'blue'); 
    cube2 = new Cube(150, 160, 20, 20, 'red'); 
    dragData.draggables.push(cube1, cube2); 
    run(); 
} 


function run() { 
    var loop = function() { 
     requestAnimationFrame(loop); 
     update(); 
     render(); 
    } 
    loop(); 
} 

function update() { 

} 

function render() { 
    ctx.clearRect(0, 0, width, height); 
    cube1.draw(ctx); 
    cube2.draw(ctx); 
} 

main();