How to make a graphics element draggable with google-closure?
How to make google closure graphics elements draggable and respond to events otherwise?
Here's what I have so far. I have the circle, but can't drag it yet :).
Thanks.
goog.开发者_StackOverflowrequire('goog.dom');
goog.require('goog.graphics');
goog.require('goog.events');
goog.require('goog.fx.Dragger');
goog.provide('graphics_test');
graphics_test = function(){
var canvas = goog.dom.createDom('div', {'id':'canvas'});
goog.dom.appendChild(document.body, canvas);
var g = goog.graphics.createGraphics(600,400);
var fill = new goog.graphics.SolidFill('yellow');
var stroke = new goog.graphics.Stroke(1,'black');
circle = g.drawCircle(300, 200, 50, stroke, fill);
var dragger = new goog.fx.Dragger(circle,circle);
g.render(goog.dom.$('canvas'));
};
I had to use a dragger in my own project and couldn't get goog.fx.Dragger to work. However, I implemented my own draggable. Its actually much smaller and pretty simple. Here is a gist:
var graphic = new goog.graphics.ext.Graphics(1000, 500);
var group = new goog.graphics.ext.Group(graphic);
group.setLeft(20, true);
group.setTop(20, true);
group.setWidth(600, true);
group.setHeight(200);
var fill = new goog.graphics.SolidFill('yellow');
var stroke = new goog.graphics.Stroke(2, 'green');
var bg = new goog.graphics.SolidFill('#eeeeee');
var outline = new goog.graphics.Stroke(1, '#333333');
var path = new goog.graphics.ext.Path().moveTo(0, 0).lineTo(20, 0).
lineTo(10, 20).close();
var shape = new goog.graphics.ext.Shape(group, path);
shape.setLeft(10, true);
shape.setTop(10, true);
shape.setWidth('10%', true);
shape.setHeight('10%');
shape.setStroke(stroke);
shape.setFill(fill);
var ellipse = new goog.graphics.ext.Ellipse(group);
ellipse.setCenter(0, true);
ellipse.setMiddle(0, true);
ellipse.setWidth(120, true);
ellipse.setHeight(60);
ellipse.setStroke(stroke);
ellipse.setFill(fill);
goog.events.listen(group.getWrapper(), 'mousedown', function(e) {
group.startOffsetX = e.offsetX;
group.startOffsetY = e.offsetY;
group.dragging = true;
});
goog.events.listen(group.getWrapper(), 'mouseup', function(e) {
group.dragging = false;
});
goog.events.listen(group.getWrapper(), 'mousemove', function(e) {
if(group.dragging) {
group.setPosition(group.getLeft() + (e.offsetX-group.startOffsetX),
group.getTop() + (e.offsetY-group.startOffsetY));
group.startOffsetX = e.offsetX;
group.startOffsetY = e.offsetY;
};
});
goog.events.listen(group.getWrapper(), 'mouseout', function(e) {
group.dragging = false;
});
graphic.render(document.body);
You can of course listen on any single shape too (rectangle/ellipse or even a path) by listening to it instead of the group itself. I feel this method gives you more flexibility (think restricting the movement of the entire group to the canvas or some custom bounds!) I purposely omitted the fifth argument(opt_handler) from goog.events.listen so as to make this code more readable.
Hope this helps :)
精彩评论