рисование canvas
Делаю простенький редактор фотографий на canvas
Есть такой код Класс рисования: function Sketch(name) { this.startDrawing = function(e) { this.isDrawing = true; this.context.beginPath(); this.context.moveTo(e.pageX - this.canvas.offsetLeft, e.pageY - this.canvas.offsetTop); } this.draw = function(e) { if (this.isDrawing == true) { var x = e.pageX - this.canvas.offsetLeft; var y = e.pageY - this.canvas.offsetTop; this.context.lineTo(x, y); this.context.stroke(); } } this.stopDrawing = function() { this.isDrawing = false; } this.isDrawing; this.canvas = document.getElementById(name); this.context = this.canvas.getContext("2d"); // Подключаем требуемые для рисования события this.canvas.onmousedown = this.startDrawing.bind(this); this.canvas.onmouseup = this.stopDrawing.bind(this); this.canvas.onmouseout = this.stopDrawing.bind(this); this.canvas.onmousemove = this.draw.bind(this); //this.canvas.bind('mousedown mouseup mousemove mouseout', this.onEvent); this.context.lineWidth = 4; this.context.strokeStyle = '#ff0'; this.context.lineJoin = "round"; this.context.lineCap = "round"; }; Т.к. редактор должен быть адаптинвым ширину и выосту картинки приходиться высчитывать пропорционально на js jQuery(document).ready(function () { var block = $('#block-canvas').width(); var new_height = (wcanvas * height) / width; if(width < block) { $('#sketch').width(width+'px'); } else { $('#sketch').width('100%'); } var wcanvas = $('#sketch').width(); var new_height = (wcanvas * height) / width; $('#sketch').height(new_height); var sketch = new Sketch('sketch'); В последней строке я запускаю класс и он работает - рисует НО расположение линий не правильное хотя координаты вроди правильные... вообщем так не объяснить, посмотрите как оно работает сейчас http://w91829a8.bget.ru/photo2/photo...er-install.jpg соответсвенно нужно что бы рисовалось правильно. Но если не задавать высоту и ширину с помощью js то рисуется правильно. В чем проблема может быть? |
Цитата:
Размеры уже нарисованного в хтмл канваса меняются через .width и .height без 'px'. Это не стили. |
И вообще, зачем ты мучаешься, если полно готовых решений. Например вот тут скачай и рисуй у себя сколько влезет. http://intridea.github.io/sketch.js/
|
Нужно указывать размер канваса, иначе он сохранит базовый размер
this.context = this.canvas.getContext("2d"); this.context.canvas.width = новая ширина; this.context.canvas.height = новая высота; |
Цитата:
И да с px или без - сути дела не меняет, работает так же |
Цитата:
|
Вот чистая выжимка из твоего компота, то есть все что у тебя там было, все четко осталось включая логику рисования, но без свистелок вроде this this this. Или ты хотел одновременно на 10-ти канвасах рисовать?
<!DOCTYPE html> <html lang="ru" dir="ltr"> <head><meta charset="utf-8"> <style> #cnvwrp { position:relative; width:100%; height:auto; outline:1px solid #aaa; } #cnvwrp canvas { cursor:crosshair; } </style> </head><body> <div tabindex="1" id="cnvwrp"></div> <script> function Sketch(opts) { var pd=false, x=function(e){return e.clientX-cnv.offsetLeft;}, y=function(e){return e.clientY-cnv.offsetTop;}, penDown = function(e) { pd = true; ctx.beginPath(); ctx.moveTo(x(e),y(e)); }, draw = function(e) { if(!pd) return; ctx.lineTo(x(e),y(e)); ctx.stroke(); }, penUp = function() { pd = false; }, div = document.getElementById(opts.id), cnv = div.appendChild(document.createElement('canvas')); cnv.heigth=opts.height; cnv.width=div.offsetWidth; ctx=cnv.getContext("2d"); for(var a in opts.init) ctx[a]=opts.init[a]; cnv.addEventListener('mousedown', penDown); cnv.addEventListener('mouseup', penUp); cnv.addEventListener('mouseout', penUp); cnv.addEventListener('mousemove', draw); }; Sketch({ id:'cnvwrp', height:400, init:{ lineWidth:5, strokeStyle:'#a00', lineJoin:'round', lineCap:'round' } }); </script> </body> </html> |
warren buffet,
x=function(e){return e.clientX-cnv.offsetLeft-8;}, y=function(e){return e.clientY-cnv.offsetTop-8;}, |
У него не было поправки на курсор, так что пусть сам говорит спасибо.
Я заменил pageX и pageY на clientX(Y) поскольку первые - сугубо специфичные свойства, которые на публике не применяются. И вообще его логика неправильная. Я не проверял как народ делает, но явно тут надо вешать листенеры на контейнер, иначе перо тупо поднимается когда доходит до края платформы. |
Надо забрать совет
Цитата:
|
Часовой пояс GMT +3, время: 02:45. |