Передвижение нескольких изображений на canvas
Здравствуйте, Уважаемые форумчане!
Хочу реализовать на canvas передвижение нескольких графических объектов, также должна быть представлена возможность изменения текстур у этих объектов. Данные графические объекты должны создаваться динамически. Т.е. при заходе пользователя на сайт он выбирает количество этих объектов и уже работает с ними. Вопрос, как лучше это сделать - прорисовывать по умолчанию на одном холсте эти объекты или создавать дополнительные canvas-ы для каждого объекта?. Т.е. дополнительный канвас отвечает за новый объект. Код с одним объектом ниже <html> <head> <style> .unselectable { -moz-user-select: -moz-none; -khtml-user-select: none; -webkit-user-select: none; -ms-user-select: none; user-select: none; } canvas{ border: 1px solid black; background-color:#cccccc; } </style> <script> var ctx; var DoorWidth = 150;//ширина двери var DoorHeight = 410;//высота двери var pic_door = new Image(); // "Создаём" изображение pic_door.src = '1.jpg'; // Источник изображения pic_door.onload = function(){ // Событие onLoad, ждём момента загрузки изображения ctx.drawImage(pic_door, 0, 0, DoorWidth, DoorHeight);// Рисуем } var canvas; var dataURL; var koef_y=40; var koef_x=30; var setTransform_x=100; var setTransform_y=100; var curid=0; var RECTS = 10; var dragok = false; // переменная истинная когда зажата кнопка мыши var x=0;//глобвльное объявление координат при перемещении обьекта var y=0;//глобвльное объявление function init(){ canvas = document.getElementById('doors'); if (canvas.getContext){ canvas.width = 1020; canvas.height = 700; ctx = canvas.getContext('2d'); canvas.onmousedown = myDown; canvas.onmouseup = myUp; return setInterval(draw, 10); } } function clear(){ ctx.setTransform(1, 0, 0, 1, 0, 0); ctx.clearRect(0, 0, canvas.width, canvas.height); //очищаем холст } function text_for_test(){ ctx.setTransform(1, 0, 0, 1, setTransform_x, -setTransform_y); ctx.font = "12px Arial"; ctx.textBaseline = "Top"; ctx.fillStyle = "black"; ctx.fillText("setTransform_x*2 "+setTransform_x*2+" м", 20, 170); ctx.fillText("Координата Х "+x, 20, 190); ctx.fillText("Координата Y "+y, 20, 210); ctx.fillText("canvas.width "+canvas.width, 20, 130); ctx.fillText("canvas.height "+canvas.height, 20, 150); } function text_nad_doors(){ ctx.setTransform(1, 0, 0, 1, setTransform_x+x, setTransform_y); ctx.beginPath(); ctx.moveTo(0,10); ctx.lineTo(0,koef_y); ctx.lineWidth = 1; ctx.strokeStyle = "#000000"; ctx.stroke(); ctx.beginPath(); ctx.moveTo(0,koef_y/2); ctx.lineTo(DoorWidth,koef_y/2); ctx.lineWidth = 1; ctx.strokeStyle = "#000000"; ctx.stroke(); ctx.beginPath(); ctx.moveTo(DoorWidth,10); ctx.lineTo(DoorWidth,koef_y); ctx.lineWidth = 1; ctx.strokeStyle = "#000000"; ctx.stroke(); ctx.font = "20px Arial"; ctx.textBaseline = "Top"; ctx.textAlign = "center"; ctx.fillStyle = "black"; ctx.fillText(DoorWidth+'0', DoorWidth/2, 10, DoorWidth); } function text_height_doors(){ ctx.setTransform(1, 0, 0, 1, setTransform_x, setTransform_y); ctx.beginPath(); ctx.moveTo(0,koef_y); ctx.lineTo(-koef_x,koef_y); ctx.lineWidth = 1; ctx.strokeStyle = "#000000"; ctx.stroke(); ctx.beginPath(); ctx.moveTo(-koef_x/2,koef_y); ctx.lineTo(-koef_x/2, DoorHeight+koef_y); ctx.lineWidth = 1; ctx.strokeStyle = "#000000"; ctx.stroke(); ctx.beginPath(); ctx.moveTo(-koef_x,DoorHeight+koef_y); ctx.lineTo(0,DoorHeight+koef_y); ctx.lineWidth = 1; ctx.strokeStyle = "#000000"; ctx.stroke(); ctx.rotate(-Math.PI / 2); // поворот на 45 градусов ctx.font = "20px Arial"; ctx.textBaseline = "Top"; ctx.textAlign = "center"; ctx.fillStyle = "black"; ctx.fillText(DoorHeight+'0', -(DoorHeight)/2-koef_y, -25); ctx.rotate(Math.PI / 2); // поворот на 45 градусов } function draw_door(){ ctx.setTransform(1, 0, 0, 1, setTransform_x+x, setTransform_y+koef_y); ctx.fillStyle = "red"; ctx.fillRect(0,0,DoorWidth,DoorHeight); texture_door(); } function texture_door() { var pat=ctx.createPattern(pic_door,"repeat"); ctx.fillStyle=pat; ctx.lineWidth = "100"; ctx.beginPath(); ctx.fillRect(0+5,0+5,DoorWidth-10,DoorHeight-15); ctx.closePath(); ctx.stroke(); } function canvas_to_png(){ dataURL = canvas.toDataURL(); document.getElementById('canvasImg').src = dataURL; } function myMove(e){ if (dragok) x = e.pageX - setTransform_x-DoorWidth/2; } function myDown(e){ x = e.pageX - canvas.offsetLeft-DoorWidth/2-setTransform_x; dragok = true; canvas.onmousemove = myMove; } function myUp(){ dragok = false; canvas.onmousemove = null; } function draw(){ clear(); //setka(); text_nad_doors(); text_height_doors(); draw_door(); text_for_test(); canvas_to_png(); } </script> <title>Двери купе</title> </head> <body onLoad="init();"> <div class="unselectable"><canvas id='doors'>Обновите браузер</canvas></div> </body> </html> |
Код с несколькими объектами на 1 холсте (переработанный скрипт, взятый с этого форума)
<!doctype html> <html> <head> <style> .unselectable { -moz-user-select: -moz-none; -khtml-user-select: none; -webkit-user-select: none; -ms-user-select: none; user-select: none; } canvas{ border: 1px solid black; background-color:#cccccc; } </style> <meta charset="UTF-8" /> <title>Canvas Drag and Drop Test</title> </head> <body> <div> <canvas id="canvas" width="400" height="300" class="unselectable"> This text is displayed if your browser does not support HTML5 Canvas. </canvas> </div> <script type="text/javascript"> var canvas = document.getElementById("canvas"); canvas.width = 1020; canvas.height = 700; var ctx = canvas.getContext("2d"); var curid=0; var RECTS = 5; var DoorWidth = 150;//ширина двери var DoorHeight = 410;//высота двери var otstup_y = 100; var pic_door = new Image(); // "Создаём" изображение pic_door.src = '1.jpg'; // Источник изображения pic_door.onload = function(){ // Событие onLoad, ждём момента загрузки изображения ctx.drawImage(pic_door, 0, 0, DoorWidth, DoorHeight);// Рисуем } function init() { return setInterval(draw, 10); } function draw() { //ctx.fillStyle = "red"; ctx.fillStyle = ctx.createPattern(pic_door,"repeat"); 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.fillRect(rect[i].x,rect[i].y,rect[i].dx,rect[i].dy); ctx.lineWidth = 5; ctx.strokeStyle = "#00ff00"; ctx.stroke(); //texture_door(); } } function texture_door() { var pat=ctx.createPattern(pic_door,"repeat"); ctx.fillStyle=pat; ctx.lineWidth = "100"; 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.fillRect(rect[i].x,rect[i].y,rect[i].dx,rect[i].dy); //ctx.stroke(); } } function Box(ctx_, id_) { this.ctx = ctx_; this.x = 75; this.y = 50; this.dx = DoorWidth; this.dy = DoorHeight; this.WIDTH = 1020; this.HEIGHT = 700; 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 myMove(e){ if (rect[curid].dragok){ rect[curid].x = e.pageX - canvas.offsetLeft-rect[curid].dx/2; rect[curid].y = otstup_y; if (rect[curid].x>canvas.width-DoorWidth*2){ rect[curid].x=canvas.width-DoorWidth*2; } if (rect[curid].x<otstup_y){ rect[curid].x=otstup_y; } } } 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)) { 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(100+i*(DoorWidth+5), otstup_y); } init(); canvas.onmouseup = myUp; canvas.onmousedown = Down; </script> </body> </html> |
а ссылка есть?
что в итоге получилось |
Цитата:
Второй вариант http://kupe-kitchen.ru/kupe_door/index.htm Во втором варианте не могу привязать текстуру к четырехугольнику |
Цитата:
и более менее подробное описание-в любом случае ибо непонятно что же надо и что не получается-кроме текстуры |
дааа, тут простыня.. не дай боже
|
Не понимаю какой из двух подходов правильный и во втором случае как привязать текстуру в объекту
|
Цитата:
|
Цитата:
|
Цитата:
нужно только самому считать на какую дверь кликнули-но так как прямоугольники то это легко считается |
для дверей нужно сделать массив-с координатами(расчитываютс во время отрисовки)-и когда кликаете нужно перебрать массив-
|
С JS нет проблем. Я не могу привязать именно в html5->canvas текстуру.
|
Цитата:
texture_door() в этой функции что то не работает? |
Вот пример, в котором реализовано что мне надо. Только для этого используется kineticjs.
http://www.html5canvastutorials.com/...invert-images/ |
Цитата:
а где здесь текстуры? Сделайте такой-же или их библиотеку используйте |
Часовой пояс GMT +3, время: 15:57. |