Добавить на canvas еще один елемент
Всем привет, следуя по примерам из сайта мозиллы и других источников сделал на canvas перемещение объекта(квадратика).
Но хоть убей не могу понять как добавить еще один квадрат и сделать его тоже перемещательным(dragging). Любые советы приветствуются! <!doctype html> <html> <head> <meta charset="UTF-8" /> <title>Canvas Drag and Drop Test</title> </head> <body> <div> <canvas id="canvas" width="400" height="300"> This text is displayed if your browser does not support HTML5 Canvas. </canvas> </div> <script type="text/javascript"> var canvas; var ctx; var x = 75; var y = 50; var dx = 5; var dy = 3; var WIDTH = 400; var HEIGHT = 300; var dragok = false; function rect(x,y,w,h) { ctx.beginPath(); ctx.rect(x,y,w,h); ctx.closePath(); ctx.fill(); } function clear() { ctx.clearRect(0, 0, WIDTH, HEIGHT); } function init() { canvas = document.getElementById("canvas"); ctx = canvas.getContext("2d"); return setInterval(draw, 10); } function draw() { clear(); ctx.fillStyle = "#FAaaaa"; rect(0,0,WIDTH,HEIGHT); ctx.fillStyle = "red"; rect(x-10, y-10, 30, 30); } function myMove(e){ if (dragok){ x = e.pageX - canvas.offsetLeft; y = e.pageY - canvas.offsetTop; } } function myDown(e){ if (e.pageX < x + 15 + canvas.offsetLeft && e.pageX > x - 15 + canvas.offsetLeft && e.pageY < y + 15 + canvas.offsetTop && e.pageY > y -15 + canvas.offsetTop){ x = e.pageX - canvas.offsetLeft; y = e.pageY - canvas.offsetTop; dragok = true; canvas.onmousemove = myMove; } } function myUp(){ dragok = false; canvas.onmousemove = null; } init(); canvas.onmousedown = myDown; canvas.onmouseup = myUp; </script> </body> </html> |
var canvas = document.getElementById("canvas"); var ctx = canvas.getContext("2d"); var WIDTH = 400; var HEIGHT = 300; function Box(ctx_, id_) { this.ctx = ctx_; this.x = 75; this.y = 50; this.dx = 15; this.dy = 15; this.id = id_; this.dragok = false; } Box.prototype.create = function() { this.ctx.beginPath(); this.ctx.rect(this.x,this.y,this.dx,this.dy); this.ctx.closePath(); this.ctx.fill(); } Box.prototype.cleare = function() { this.ctx.beginPath(); this.ctx.clearRect(this.x, this.y, this.dx, this.dy); this.ctx.closePath(); this.ctx.fill(); } Box.prototype.getX = function() { return (this.x + canvas.offsetLeft); } Box.prototype.getY = function() { return (this.y + canvas.offsetTop); } Box.prototype.isFocus = function(mX,mY) { if(mX>this.getX() && mY>this.getY() && mX<(this.getX() + this.dx) && mY<(this.getY() + this.dy)) return true; else return false; } function getRandomArbitary(min, max) { return Math.random() * (max - min) + min; } function clear() { ctx.clearRect(0, 0, WIDTH, HEIGHT); } function GetId(mX,mY) { for(p in rect) { if(rect[p].isFocus(mX,mY)) { return rect[p].id; } } } function draw() { clear(); for(p in rect) { rect[p].create(); } } function Move(e){ var id = GetId(e.pageX,e.pageY); rect[id].x = e.pageX - canvas.offsetLeft; rect[id].y = e.pageY - canvas.offsetTop; } function Up(){ canvas.onmousemove = null; } function Down(){ canvas.onmousemove = Move; } var rect = new Array(3); for(var i=0; i<3 ; i++) { rect[i] = new Box(ctx,i); rect[i].x = getRandomArbitary(0, 300); rect[i].y = getRandomArbitary(0, 260); rect[i].create(); } setInterval(draw, 10); canvas.onmousedown = Down; canvas.onmouseup = Up; Немного переработал скрипт. Есть баги небольшие, отладишь сам. |
Спасибо, попробую дома как оно будет
|
Я немного допилил твой скрипт, вроди все круто вышло
<!doctype html> <html> <head> <meta charset="UTF-8" /> <title>Canvas Drag and Drop Test</title> </head> <body> <div> <canvas id="canvas" width="400" height="300"> This text is displayed if your browser does not support HTML5 Canvas. </canvas> </div> <script type="text/javascript"> var canvas = document.getElementById("canvas"); var ctx = canvas.getContext("2d"); var curid=0; var RECTS = 10; function init() { return setInterval(draw, 10); } function draw() { ctx.clearRect(0, 0, rect[0].WIDTH, rect[0].HEIGHT); for(i=0;i<RECTS;i++){ ctx.beginPath(); ctx.rect(rect[i].x,rect[i].y,rect[i].dx,rect[i].dy); ctx.closePath(); ctx.fill(); } } function Box(ctx_, id_) { this.ctx = ctx_; this.x = 75; this.y = 50; this.dx = 30; this.dy = 30; this.WIDTH = 400; this.HEIGHT = 300; this.id = id_; this.dragok = false; } Box.prototype.create = function(x,y) { this.x = x; this.y = y; this.ctx.beginPath(); this.ctx.rect(x,y,this.dx,this.dy); this.ctx.closePath(); this.ctx.fill(); } Box.prototype.cleare = function() { this.ctx.clearRect(this.x, this.y, this.dx, this.dy); } Box.prototype.getX = function() { return (this.x + canvas.offsetLeft); } Box.prototype.getY = function() { return (this.y + canvas.offsetTop); } Box.prototype.isFocus = function(mX,mY) { if(mX>this.getX() && mY>this.getY() && mX<(this.getX() + this.dx) && mY<(this.getY() + this.dy)) return true; else return false; } function getRandomArbitary(min, max) { return Math.random() * (max - min) + min; } function myMove(e){ if (rect[curid].dragok){ rect[curid].x = e.pageX - canvas.offsetLeft-rect[curid].dx/2; rect[curid].y = e.pageY - canvas.offsetTop-rect[curid].dy/2; } } function myUp(){ rect[curid].dragok = false; curid = 0; canvas.onmousemove = null; } function Move(mX, mY){ for(p in rect) { if(rect[p].isFocus(mX,mY)) { //alert("p="+p+", rect[p].id="+rect[p].id); //rect[p] объект с которым продолжим работат (Тот на который нажали мышкой); //alert("x="+rect[p].x+", mX="+mX); //rect[p].x = mX-canvas.offsetLeft; //rect[p].y = mY-canvas.offsetTop; rect[p].dragok = true; curid=p; canvas.onmousemove = myMove; } } } function Down(event) { Move(event.pageX,event.pageY); } var rect = new Array(RECTS); for(var i=0; i<RECTS; i++) { rect[i] = new Box(ctx,i); rect[i].create(getRandomArbitary(0, 300),getRandomArbitary(0, 260)); } init(); canvas.onmouseup = myUp; canvas.onmousedown = Down; </script> </body> </html> |
Класс. Мне самому нравится. Может где тоже использую такую фишку. Смотри еще что, возможно стоит немного разгрузить программу.
function draw() { ctx.clearRect(0, 0, rect[0].WIDTH, rect[0].HEIGHT); for(i=0;i<RECTS;i++){ rect[i].create(rect[i].x,rect[i].y,rect[i].dx,rect[i].dy); } } И вызывать её только тогда когда объект движется. function myUp(){ rect[curid].dragok = false; curid = 0; canvas.onmousemove = null; clearInterval(interval); } function Down(event) { Move(event.pageX,event.pageY); interval = setInterval(draw, 10); } var interval; |
MadGest,
Да, спасибо, так выглядит более элегантней |
Часовой пояс GMT +3, время: 04:26. |