theshock / libcanvas Goto Github PK
View Code? Open in Web Editor NEWLibCanvas - Canvas Javascript library
Home Page: http://libcanvas.com
LibCanvas - Canvas Javascript library
Home Page: http://libcanvas.com
Будет ли поддержка webpack и npm?
measureText не верно рассчитывает ширину текста.
Тут скорее всего должна вызываться функция apply
вместо call
https://github.com/theshock/libcanvas/blob/master/Source/Context/Text.js#L61
http://i.imgur.com/LznJLJA.png
Code:
new Line(100, 100, 150, 100)
.distanceTo( new Point(95, 100), false );
Expected: 5
Result: 0
Description:
If point
is on infinity line it returns zero always
Например для обычного контекста canvas.getContext('2d', {alpha: false})
актуально для Хрома
Для getContext('2d-libcanvas')
опции теряются
Пулл сделаю чуть позже
I'm rendering paths and don't want the framework to automatically call closePath() on them. Is there a way of doing this without subclassing Path and overriding methods? Would definitely be a useful feature to have a flag on the Path Class, something like "autoClose", set to true by default to keep existing code as before
Я не понимаю что такой объект Color и функция getPixel. Скажите на такой интересный вопрос: возможно ли физически изменить/удалить фигуру, а визуально не трогать? При этом события не врубались заново?
У меня какая идея - хочу, когда навожу по картинке (не, речь не о 1м ректов) менялась фигура. При этом корректно работали события, хотя я меняю фигуру (крупный квадрат/нету квадрата) при помощи определения цвета пикселя.
Мне хотелось бы сделать draggable картиночный объект не методом over 9000 а методом определения цвета и изменения фигуры.
Если вы меня не правильно поняли речь идет: если под курсором исчезла фигура - сработало mouseout и события заднего плана если оно есть. Если фигура под курсором есть, несмотря на то что обновилась/осталась неизменной (а пока цвет не поменяется, оно всегда будет неизменной) была событие mousemove. Если под курсором только что появилась фигура - mouseover.
Задумка интересная реальна - визуальная картинка и невидимый рект, который может появляется/пропадать при наведении по картинки (точнее по ее пикселям).
Мне сложнее всего сделать так, чтобы курсор определял цвет пикселей самой картинки, а не всего контекста.
Если идея все равно не понятно, ну и * с вами...
Снова здравствуйте.
Намедни использовал тайловый движок в своем проекте и заметил недокументированное поведение:
используя Element.app(...) параметр from действительно является опциональным (https://github.com/theshock/libcanvas/blob/master/Source/Engines/Tile/Element.js#L48). Однако при вызове конструктора Element(...) можно столкнуться с тем, что неуказанный параметр from в итоге проходит как undefined и далее все падает.(https://github.com/theshock/libcanvas/blob/master/Source/Engines/Tile/Element.js#L25)
Приятного Вам дня.
It would be great if you added functionality for flipping/scaling image into drawImage method.
Thanks.
У меня не получается повесить обработчик dblclick.
Хотелось бы при dblclick на объекте открыть новое окно.
initialize: function (module, wide) {
var shape = new RoundedRectangle(Monitoring.modulepos.x, Monitoring.modulepos.y, 10+wide*10, 25).setRadius(5);
this.setShape(shape);
this.listenMouse().clickable().draggable();
this.addEvent('dblclick', function (e) {
this.trace.value = "dblclick";
// window.open('test5.html','BASE', "width=800, height=600,' toolbar=no, scrollbars=no,resizable=no, status=no', left=0,top=0");
});
Hi,
is there any way to apply gradients to existing shaper object?
the example @ http://libcanvas.github.com/ui/gradients.html is rather complicated and requires creating custom classes and overriding draw functions, 'just to apply gradient'.
Я предлагаю ввести новую фигуру - пиксельная карта. По сути это rect'ы любого размера. Они позволяют создавать маски нестандартного размера для изображений.
Вот почему в Path.Builder нету такой фигуры как rect ? Почему там только линии и bezier?
Есть очень много очень сложных изображений, к примеру: http://www.html5canvastutorials.com/demos/labs/html5_canvas_animal_beach_game/lion.png
Вы разве подберете такую фигуру в точности? НЕТ!
Я на KineticJS уже давно реализовал (http://jnglike.site40.net/examples/image.html), правда пашет стабильно на небольших картинках. При 256х256 начинает немного лагать. При 512х512 и выше - сильные лаги. При 1024х1024 - зависания до 1 минуты.
И я прошу никогда не отвергать идеи когда это важно всем!
is:
weigth : 'normal', /* bold|normal */
should be:
weight : 'normal', /* bold|normal */
Имеется ли возможность добавить уже существующие canvas элементы как слои в инициализированный libcanvas?
would be nice to be able specify shadows on Shaper class, same way as stroke or fill to achieve something like this:
context.shadowOffsetX = 0;
context.shadowOffsetY = 0;
context.shadowBlur = 4;
context.shadowColor = '#303030';
now I have to override drawing of a particular shape and do it manually there, but shadows could ideally be generic part of the framework
Hi,
I have a libcanvas with lots of shapes on it, which is dramatically reducing performance of the application. The objects are moving around, animating etc... are there any basic performance tips as how to handle these situation to get good performance.
I've tried to do
libcanvas.freeze()
[handle all the moving of objects]
libcancas.freeze(false),
but that seems to stop rendering alltogether.
Is there any buffering that I could use?
Thanks,
Stevo
Hi, I'm very new to libcanvas and canvas in general. I would like to fire a callback event when the fifteen puzzle (from your examples) has been completed. How should I go about doing that?
I wouldn't normally create an issue for a question but I have been unable to find another way to contact you.
We at VersionEye are working hard to keep up the quality of the bower's registry.
We just finished our initial analysis of the quality of the Bower.io registry:
7530 - registered packages, 224 of them doesnt exists anymore;
We analysed 7306 existing packages and 1070 of them don't have bower.json on the master branch ( that's where a Bower client pulls a data ).
Sadly, your library theshock/libcanvas
is one of them.
Can you spare 15 minutes to help us to make Bower better?
Just add a new file bower.json
and change attributes.
{
"name": "theshock/libcanvas",
"version": "1.0.0",
"main": "path/to/main.css",
"description": "please add it",
"license": "Eclipse",
"ignore": [
".jshintrc",
"**/*.txt"
],
"dependencies": {
"<dependency_name>": "<semantic_version>",
"<dependency_name>": "<Local_folder>",
"<dependency_name>": "<package>"
},
"devDependencies": {
"<test-framework-name>": "<version>"
}
}
Read more about bower.json on the official spefication and nodejs semver library has great examples of proper versioning.
NB! Please validate your bower.json with jsonlint before commiting your updates.
Thank you!
Timo,
twitter: @versioneye
email: [email protected]
VersionEye - no more legacy software!
Я предлагаю ввести поддержку событий на картинках! Эта функция уже реализована БЕЗ ЛАГОВ!
http://solovei95.github.com/jng/dev/
Он не использует 1.000.000 квадратов, а определяет альфа-канал. Метод особо наглый!
Я знаю, что у пользователей накопилась гора вопросов, идей, бреда, оскорблений, критики и оценок. Я прошу сделать официальный сайт libcanvas и atomjs.
Пустой мир! Ноль идей. Один разраб... Лучше бы меня забанили...
Using the examples from the demo website, I've tried to create a simple path and animate fill alpha in a loop animation:
var path = new Path.Builder()
.move(200, 50)
.line(300, 50)
.curve(250, 150, 350, 125, 240, 60)
.arc({
circle: new Circle(200, 150, 50),
angle: [0, (270).degree()]
})
.snapToPixel()
.build();
var shape = this.libCanvas.createShaper({
shape: path,
fill: 'rgba(255, 0, 0, 1)'
});
shape.animate({
props: {
fill: 'rgba(254, 0, 0, 0.1)'
},
time: 600,
onFinish: function (prevAnim, prevProps) {
shape.animate({
props: prevProps,
fn: 'bounce-out',
time: 400,
onFinish: prevAnim.repeat
});
}
});
the Alpha doesn't get animated. I'm doing something wrong? Basically I'm trying to fade-in/out objects
Hi,
I'm trying to implement a fire effect described in here
http://me.murphybob.com/2011/07/retro-fire-in-html5-canvas/
I can get it to work, but I have one problem - I need the fire 'background' to be transparent, as I'm moving the fire 'element' around the canvas, on top other elements. The underlying problem lies in:
putImageData
it doesn't render on top, it basically overrides what's underneath. I'm sure you're aware of this, but just in case it's discussed here http://stackoverflow.com/questions/5210874/html5-canvas-image-caching-putimagedata-questions
So I'd need to take advantage of layers or something similar, any ideas how to implement something like that?
Thanks!
Windows 10
Chrome 43 (в FairFox проблема не наблюдается)
Видео с демонстрацией проблемы (1.14 Мб, GIF-файл)
https://dl.dropboxusercontent.com/u/54210112/libcanvas.gif
Скажите, как получить пиксель только с района фигуры? Мне просто надо вычислить альфа-канал с Image с районом Rect.
Is there a way to delay animation start? Something like this:
shape.animate({
props: {
stroke: 'rgba(255, 210, 0, 0)'
},
time: 1000,
onFinish: function (prevAnim, prevProps) {
lastSectorYellow.animate({
props: prevProps,
time: 1000,
start: 1000, <<<<<<<<<<<<<<<<<<<<<<<<<<<
onFinish: prevAnim.repeat
});
}
});
so the object stays in the animated state for a period of time, rather then reverting back immediately
Я думаю, что в libcanvas нужно ввести поддержку jng. Я пока что не выложил на github JNG скрипт, но я уверен, он вам подойдет. Вот его демо страница: http://jnglike.site40.net/
В событиях клавиатуры в Chrome выдает такое предупреждение.
event.layerX and event.layerY are broken and deprecated in WebKit. They will be removed from the engine in the near future
How do you intend to handle the order in which the shapes are drawn, I can't find a way of swapping item's z-order. Could be a method of the Shape class - moveUp() moveDown() moveToZIndex(index). Currently the libcanvas in rendering in reverse order of a standard html canvas - first item created is drawn last.
Hi,
is there a way of rotating any shape, or shaper? There is a method on Path that allowes it to rotate it by custom angle, but no other shape seems to support rotation?
thanks
В общем суть такова. Постоянно валится ошибка Uncaught TypeError: Cannot call method 'hasPoint' of undefined
Происходит при условии что Rectangle становится Draggable.
Смог пофиксить следующим методом:
hasPoint: function (point) {
if(!this.shape) this.shape = this.rect
return this.shape.hasPoint( point );
},
Правда какой баг после этого вылезет, еще не знаю.
Если надо, могу кинуть свой говно-код для анализа(
Maybe, we should rewrite ctx.drawImage - too many overhead operations. Code for profiling:
var ctx = atom.dom('canvas').first.getContext('2d-libcanvas');
ctx.width = 400;
ctx.height = 300;
var img = new Image();
img.src = 'http://libcanvas.github.com/files/img/html5-logo-small.png';
var points = Array.range(0, 500).map(function () {
return new LibCanvas.Point(
Number.random(0, 350),
Number.random(0, 250)
);
});
function redraw () {
ctx.clearAll();
for (var i = 500; i--;) {
var point = points[i];
if (point.x > 350) point.x = 0;
else point.x++;
ctx.drawImage({ image: img, from: point });
}
};
img.onload = function () {
atom.frame.add(redraw);
}
Hi
would be nice to have a text shape class, so one can render text and manipulate same way as other shapes. Just a suggestion.
Thanks,
Stevo
Код :
new LibCanvas.Shapes.Rectangle({
from: [4, 4],
to: [10, 10]
}).hasPoint([4, 4]);
Возвращает false, а должен true
Код :
var rect = new LibCanvas.Shapes.Rectangle({
from: [4, 4],
to: [10, 10]
});
new LibCanvas.Shapes.Rectangle({
from: [10, 10],
to: [15, 15]
}).intersect(rect);
Возвращает false, а должен true.
Почему-то вместо нестрогих неравенств используются строгие.
При клике первый раз в любом месте вызываются обработчики нажатия мыши всех объектов. (см. консоль)
http://pastebin.com/LJNXuVHZ
Hi,
how can I specify the direction of linear gradient?
the example @ http://libcanvas.github.com/ui/gradients.html goes from top left corner to bottom right corner. I'd like to have a vertical gradient.
Пытаюсь добавить обработчик на клик по элементам, которые наследуют Draggable. Однако 'click' фактически работает как 'mouseup', т.е. не отличает собственно клик и нажатие-перемещение-отпускание клавиши. Это видно даже в примере: http://libcanvas.github.com/scenes/
Если это фича, то как обойти её?
Метод "getCellByIndex" у тайлового движка не принимает точку в виде "[x, y]" ( требует "new Point(x, y)" )
тоже самое у ".getCellByPoint"
What is the correct way or removing and disposing all shapes from libCanvas object?
currently I do:
libCanvas.rmAllElements();
but I'm experiencing a problem with attached event handlers. If any of the existing shapes have attached even handlers:
shaper.listenMouse().clickable();
shaper.addEvent(['mousedown'], function (e) { alert('mousedown'); });
those event handers still trigger, even after the shape was removed from the canvas.
Вот небольшой пример: http://gost-plan-test.s3-website-eu-west-1.amazonaws.com/
Но периодически рисунок не появляется, хотя дебаггер хрома говорит, что он загружен.
Я использую код из примеров, так что по сути там всё достаточно стандартно. Есть ImageDrawer (копия того, который в примерах). Все картинки грузятся через
new LibCanvas('canvas', {
preloadImages:{
info_red :'images/info_red.png',
info_green :'images/info_green.png',
info_blue :'images/info_blue.png',
info_yellow:'images/info_yellow.png',
plan :'images/plan.png'
}})
и инициализируются через
.start()
.addEvent('ready', function () {
var img = this.getImage('plan');
new ImageDrawer(this, 'plan', [0, 0, img.width, img.height]);
})
.update();
Если открылась пустая страница, то если пару раз обновить, то рисунок появляется. При чем лог всегда говорит:
Image preloading has completed;
Images loaded: 5; Errors: 0; Aborts: 0
В чем может быть проблема?
just open this demo link in latest Opera http://libcanvas.github.com/animating/looped.html and watch that is animating much faster than in any other browser
The LibCanvas isn't true handles this code:
This example is "false":
layer.ctx
.set({ lineCap: 'round', lineWidth: 10 })
.stroke(line);
This example is "true":
layer.ctx
.beginPath()
.moveTo(line.from)
.lineTo(line.to)
.set({ lineCap: 'round', lineWidth: 10 })
.stroke()
.closePath();
See more on jsfiddle
http://libcanvas.github.com/shapes/rectangle/creating.html
press mouse at the center and move it fast to right out of canvas
http://clip2net.com/clip/m46295/1304603293-cliptj2185-36kb.png
http://libcanvas.github.com/shapes/rectangle/points.html
press mouse at the block - move it out of canvas - move event stopped
if you move it back - nothing happends
maybe it will be more usefull as mousemove event:
a) bind mousemove to window
b) if mouse is out of canvas: trigger event at the nearest point at the canvas's border
c) if mouse is still out of canvas
if some config flag defined: do nothing
if some config flag not defined: trigger event at the nearest point at the canvas's border
what do you think about it?
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.