Giter Club home page Giter Club logo

libcanvas's People

Contributors

0x000000 avatar a13ks3y avatar firevolkhov avatar hronex avatar jwo1f avatar maniulo avatar quby avatar stfalcon avatar svtux avatar theshock avatar vbo avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

libcanvas's Issues

Line distance to - zero result

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

Enhancement: Path that doesn't automatically call closePath();

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.

Задумка интересная реальна - визуальная картинка и невидимый рект, который может появляется/пропадать при наведении по картинки (точнее по ее пикселям).

Мне сложнее всего сделать так, чтобы курсор определял цвет пикселей самой картинки, а не всего контекста.
Если идея все равно не понятно, ну и * с вами...

Баг в Engines.Tile.Element

Снова здравствуйте.
Намедни использовал тайловый движок в своем проекте и заметил недокументированное поведение:
используя 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)

Приятного Вам дня.

Обработка dblclick

У меня не получается повесить обработчик 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");
});

Новая фигура - pixelmap

Я предлагаю ввести новую фигуру - пиксельная карта. По сути это 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 минуты.

И я прошу никогда не отвергать идеи когда это важно всем!

Support for shadows?

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

Optimizing performance

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

Fire callback when fifteen puzzle has been completed

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.

[enhancement] Add missing bower.json.

Hey, maintainer(s) of theshock/libcanvas!

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 квадратов, а определяет альфа-канал. Метод особо наглый!

Проблемы

  1. Я заметил, что документация не полная.
  2. Вопросы задавать некуда. Все программисты не опытные и не знают libcanvas.
  3. Будете делать форум наконец для libcanvas?

Я знаю, что у пользователей накопилась гора вопросов, идей, бреда, оскорблений, критики и оценок. Я прошу сделать официальный сайт libcanvas и atomjs.

Пустой мир! Ноль идей. Один разраб... Лучше бы меня забанили...

Animating alpha (fade-in/out) not showing

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

Implementing Fire effect

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!

Delaying animation start?

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

JNG скрипт в libcanvas

Я думаю, что в libcanvas нужно ввести поддержку jng. Я пока что не выложил на github JNG скрипт, но я уверен, он вам подойдет. Вот его демо страница: http://jnglike.site40.net/

Handling of shape z-index ?

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.

Rotate Shape (Rectangle)

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

this.shape.hasPoint - ошибка

В общем суть такова. Постоянно валится ошибка 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 );
},

Правда какой баг после этого вылезет, еще не знаю.
Если надо, могу кинуть свой говно-код для анализа(

Optimize drawImage

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);
}

Text 'shape' enhancement suggestion

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

LibCanvas.Shapes.Rectangle.hasPoint

Код :

 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.

Почему-то вместо нестрогих неравенств используются строгие.

'click' всегда следует за 'stopDrag'

Пытаюсь добавить обработчик на клик по элементам, которые наследуют Draggable. Однако 'click' фактически работает как 'mouseup', т.е. не отличает собственно клик и нажатие-перемещение-отпускание клавиши. Это видно даже в примере: http://libcanvas.github.com/scenes/
Если это фича, то как обойти её?

Correct way of removing/disposing all shapes

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

В чем может быть проблема?

style of lineCap

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

mousemove out of canvas

  1. 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

  2. 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?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.