Add Canvas.base.request and finally make demo page work. Remove remnants of Prototype.js from fabric.js.

This commit is contained in:
Juriy Zaytsev 2010-06-24 03:37:02 -04:00
parent 9e1bf5b322
commit 8ee515e647
9 changed files with 522 additions and 34 deletions

434
dist/all.js vendored
View file

@ -522,7 +522,7 @@ if (!Array.prototype.reduce) {
function invoke(array, method) {
var args = slice.call(arguments, 2), result = [ ];
for (var i = 0, len = array.length; i < len; i++) {
result[i] = method.apply(array[i], args);
result[i] = args.length ? method.apply(array[i], args) : method.call(array[i]);
}
return result;
}
@ -1032,6 +1032,68 @@ Canvas.base.addClass = addClass;
Canvas.base.wrapElement = wrapElement;
Canvas.base.getElementOffset = getElementOffset;
(function(){
function addParamToUrl(url, param) {
return url + (/\?/.test(url) ? '&' : '?') + param;
}
var makeXHR = (function() {
var factories = [
function() { return new ActiveXObject("Microsoft.XMLHTTP"); },
function() { return new ActiveXObject("Msxml2.XMLHTTP"); },
function() { return new ActiveXObject("Msxml2.XMLHTTP.3.0"); },
function() { return new XMLHttpRequest(); }
];
for (var i = factories.length; i--; ) {
try {
var req = factories[i]();
if (req) {
return factories[i];
}
}
catch (err) { }
}
})();
function emptyFn() { };
function request(url, options) {
options || (options = { });
var method = options.method ? options.method.toUpperCase() : 'GET',
onComplete = options.onComplete || function() { },
request = makeXHR(),
body;
request.onreadystatechange = function() {
if (request.readyState === 4) {
onComplete(request);
request.onreadystatechange = emptyFn;
}
};
if (method === 'GET') {
body = null;
if (typeof options.parameters == 'string') {
url = addParamToUrl(url, options.parameters);
}
}
request.open(method, url, true);
if (method === 'POST' || method === 'PUT') {
request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
}
request.send(body);
return request;
};
Canvas.base.request = request;
})();
})(this);
(function(){
@ -1345,7 +1407,7 @@ Canvas.base.getElementOffset = getElementOffset;
*/
function parseElements(elements, options) {
var _elements = elements.map(function(el) {
var klass = Canvas[el.tagName.capitalize()];
var klass = Canvas[Canvas.base.string.capitalize(el.tagName)];
if (klass && klass.fromElement) {
try {
return klass.fromElement(el, options);
@ -1427,7 +1489,7 @@ Canvas.base.getElementOffset = getElementOffset;
height: height
};
var elements = Canvas.parseElements(elements, Object.clone(options));
var elements = Canvas.parseElements(elements, Canvas.base.object.clone(options));
if (!elements || (elements && !elements.length)) return;
if (callback) {
@ -2120,9 +2182,9 @@ Canvas.base.getElementOffset = getElementOffset;
Canvas.base.object.extend(Canvas.Element.prototype, {
selectionColor: 'rgba(100,100,255,0.3)', // blue
selectionBorderColor: 'rgba(255,255,255,0.3)', // white
selectionBorderColor: 'rgba(255,255,255,0.3)',
selectionLineWidth: 1,
backgroundColor: 'rgba(255,255,255,1)', // white
backgroundColor: 'rgba(255,255,255,1)',
includeDefaultValues: true,
shouldCacheImages: false,
@ -2130,9 +2192,6 @@ Canvas.base.getElementOffset = getElementOffset;
CANVAS_WIDTH: 600,
CANVAS_HEIGHT: 600,
CANVAS_PRINT_WIDTH: 3000,
CANVAS_PRINT_HEIGHT: 3000,
onBeforeScaleRotate: function () {
/* NOOP */
},
@ -3851,10 +3910,10 @@ Canvas.base.getElementOffset = getElementOffset;
*/
dispose: function () {
this.clear();
Event.stopObserving(this.getElement(), 'mousedown', this._onMouseDown);
Event.stopObserving(document, 'mouseup', this._onMouseUp);
Event.stopObserving(document, 'mousemove', this._onMouseMove);
Event.stopObserving(window, 'resize', this._onResize);
Canvas.base.removeListener(this.getElement(), 'mousedown', this._onMouseDown);
Canvas.base.removeListener(document, 'mouseup', this._onMouseUp);
Canvas.base.removeListener(document, 'mousemove', this._onMouseMove);
Canvas.base.removeListener(window, 'resize', this._onResize);
return this;
},
@ -3891,8 +3950,8 @@ Canvas.base.getElementOffset = getElementOffset;
_resizeImageToFit: function (imgEl) {
var widthScaleFactor = 1, //this.CANVAS_WIDTH / this.CANVAS_PRINT_WIDTH,
heightScaleFactor = 1, //this.CANVAS_HEIGHT / this.CANVAS_PRINT_HEIGHT,
var widthScaleFactor = 1,
heightScaleFactor = 1,
imageWidth = imgEl.width || imgEl.offsetWidth,
imageHeight = imgEl.height || imgEl.offsetHeight;
@ -5958,7 +6017,8 @@ Canvas.base.getElementOffset = getElementOffset;
throw Error('`path` argument is required');
}
var fromArray = Object.isArray(path);
var fromArray = Object.prototype.toString.call(path) === '[object Array]';
this.path = fromArray
? path
: path.match && path.match(/[a-zA-Z][^a-zA-Z]*/g);
@ -7187,3 +7247,347 @@ Canvas.base.getElementOffset = getElementOffset;
Canvas.Text.fromElement = function(element) {
};
})();
(function() {
var global = this;
if (!global.Canvas) {
global.Canvas = { };
}
if (global.Canvas.Image) {
console.warn('Canvas.Image is already defined.');
return;
};
if (!Canvas.Object) {
console.warn('Canvas.Object is required for Canvas.Image initialization');
return;
}
Canvas.Image = Canvas.base.createClass(Canvas.Object, {
maxwidth: null,
maxheight: null,
active: false,
bordervisibility: false,
cornervisibility: false,
type: 'image',
__isGrayscaled: false,
/**
* @constructor
* @param {HTMLImageElement | String} element Image element
* @param {Object} options optional
*/
initialize: function(element, options) {
this.callSuper('initialize', options);
this._initElement(element);
this._initConfig(options || { });
},
/**
* @method getElement
* @return {HTMLImageElement} image element
*/
getElement: function() {
return this._element;
},
/**
* @method setElement
* @return {Canvas.Image} thisArg
*/
setElement: function(element) {
this._element = element;
return this;
},
/**
* Method that resizes an image depending on whether maxwidth and maxheight are set up.
* Width and height have to mantain the same proportion in the final image as it was in the initial one.
* @method getNormalizedSize
* @param {Object} oImg
* @param {Number} maximum width of the image in px
* @param {Number} maximum height of the image in px
*/
getNormalizedSize: function(oImg, maxwidth, maxheight) {
if (maxheight && maxwidth && (oImg.width > oImg.height && (oImg.width / oImg.height) < (maxwidth / maxheight))) {
normalizedWidth = Math.floor((oImg.width * maxheight) / oImg.height);
normalizedHeight = maxheight;
}
else if (maxheight && ((oImg.height == oImg.width) || (oImg.height > oImg.width) || (oImg.height > maxheight))) {
normalizedWidth = Math.floor((oImg.width * maxheight) / oImg.height);
normalizedHeight = maxheight;
}
else if (maxwidth && (maxwidth < oImg.width)){
normalizedHeight = Math.floor((oImg.height * maxwidth) / oImg.width);
normalizedWidth = maxwidth;
}
else {
normalizedWidth = oImg.width;
normalizedHeight = oImg.height;
}
return {
width: normalizedWidth,
height: normalizedHeight
}
},
/**
* @method getOriginalSize
* @return {Object} object with "width" and "height" properties
*/
getOriginalSize: function() {
var element = this.getElement();
return {
width: element.width,
height: element.height
};
},
/**
* @method setBorderVisibility
* @param showBorder {Boolean} when true, border is being set visible
*/
setBorderVisibility: function(showBorder) {
this._resetWidthHeight();
this._adjustWidthHeightToBorders(showBorder);
this.setCoords();
},
/**
* @method setCornersVisibility
*/
setCornersVisibility: function(visible) {
this.cornervisibility = !!visible;
},
/**
* @method render
*/
render: function(ctx, noTransform) {
ctx.save();
if (!noTransform) {
this.transform(ctx);
}
this._render(ctx);
if (this.active && !noTransform) {
this.drawBorders(ctx);
this.hideCorners || this.drawCorners(ctx);
}
ctx.restore();
},
/**
* @method toObject
* @return {Object} object representation of an instance
*/
toObject: function() {
return Canvas.base.object.extend(this.callSuper('toObject'), {
src: this.getSrc()
});
},
/**
* @method getSrc
* @return {String} source of an image
*/
getSrc: function() {
return this.getElement().src;
},
/**
* @method toString
* @return {String} string representation of an instance
*/
toString: function() {
return '#<Canvas.Image: { src: "' + this.getSrc() + '" }>';
},
/**
* @mthod clone
* @param {Function} callback
*/
clone: function(callback) {
this.constructor.fromObject(this.toObject(), callback);
},
/**
* @mthod toGrayscale
* @param {Function} callback
*/
toGrayscale: function(callback) {
if (this.__isGrayscaled) {
return;
}
var imgEl = this.getElement(),
canvasEl = document.createElement('canvas'),
replacement = document.createElement('img'),
_this = this;
canvasEl.width = imgEl.width;
canvasEl.height = imgEl.height;
canvasEl.getContext('2d').drawImage(imgEl, 0, 0);
Canvas.Element.toGrayscale(canvasEl);
replacement.onload = function() {
_this.setElement(replacement);
callback && callback();
replacement.onload = canvasEl = imgEl = imageData = null;
};
replacement.width = imgEl.width;
replacement.height = imgEl.height;
replacement.src = canvasEl.toDataURL('image/png');
this.__isGrayscaled = true;
return this;
},
/**
* @private
*/
_render: function(ctx) {
var originalImgSize = this.getOriginalSize();
ctx.drawImage(
this.getElement(),
- originalImgSize.width / 2,
- originalImgSize.height / 2,
originalImgSize.width,
originalImgSize.height
);
},
/**
* @private
*/
_adjustWidthHeightToBorders: function(showBorder) {
if (showBorder) {
this.currentBorder = this.borderwidth;
this.width += (2 * this.currentBorder);
this.height += (2 * this.currentBorder);
}
else {
this.currentBorder = 0;
}
},
/**
* @private
*/
_resetWidthHeight: function() {
var element = this.getElement();
this.set('width', element.width);
this.set('height', element.height);
},
/**
* The Image class's initialization method. This method is automatically
* called by the constructor.
* @method _initElement
* @param {HTMLImageElement|String} el The element representing the image
*/
_initElement: function(element) {
this.setElement(Canvas.base.getById(element));
Canvas.base.addClass(this.getElement(), Canvas.Image.CSS_CANVAS);
},
/**
* @method _initConfig
* @param {Object} options Options object
*/
_initConfig: function(options) {
this.setOptions(options);
this._setBorder();
this._setWidthHeight(options);
},
/**
* @private
*/
_setBorder: function() {
if (this.bordervisibility) {
this.currentBorder = this.borderwidth;
}
else {
this.currentBorder = 0;
}
},
/**
* @private
*/
_setWidthHeight: function(options) {
var sidesBorderWidth = 2 * this.currentBorder;
this.width = (this.getElement().width || 0) + sidesBorderWidth;
this.height = (this.getElement().height || 0) + sidesBorderWidth;
}
});
/**
* Constant for the default CSS class name that represents a Canvas
* @property Canvas.Image.CSS_CANVAS
* @static
* @final
* @type String
*/
Canvas.Image.CSS_CANVAS = "canvas-img";
/**
* Creates an instance of Canvas.Image from its object representation
* @method fromObject
* @param object {Object}
* @param callback {Function} optional
* @static
*/
Canvas.Image.fromObject = function(object, callback) {
var img = document.createElement('img'),
src = object.src;
if (object.width) {
img.width = object.width;
}
if (object.height) {
img.height = object.height;
}
img.onload = function() {
if (callback) {
callback(new Canvas.Image(img, object));
}
img = img.onload = null;
};
img.src = src;
};
/**
* Creates an instance of Canvas.Image from an URL string
* @method fromURL
* @param url {String}
* @param callback {Function} optional
* @param imgOptions {Object} optional
* @static
*/
Canvas.Image.fromURL = function(url, callback, imgOptions) {
var img = document.createElement('img');
img.onload = function() {
if (callback) {
callback(new Canvas.Image(img, imgOptions));
}
img = img.onload = null;
};
img.src = url;
};
})();

View file

@ -25,4 +25,6 @@
//= require "src/canvas_group.class"
//= require "src/canvas_text.class"
//= require "src/canvas_text.class"
//= require "src/canvas_image.class"

View file

@ -15,4 +15,6 @@
//= require "canvas_base/dom_style"
//= require "canvas_base/dom_misc"
//= require "canvas_base/dom_request"
})(this);

View file

@ -0,0 +1,61 @@
(function(){
function addParamToUrl(url, param) {
return url + (/\?/.test(url) ? '&' : '?') + param;
}
var makeXHR = (function() {
var factories = [
function() { return new ActiveXObject("Microsoft.XMLHTTP"); },
function() { return new ActiveXObject("Msxml2.XMLHTTP"); },
function() { return new ActiveXObject("Msxml2.XMLHTTP.3.0"); },
function() { return new XMLHttpRequest(); }
];
for (var i = factories.length; i--; ) {
try {
var req = factories[i]();
if (req) {
return factories[i];
}
}
catch (err) { }
}
})();
function emptyFn() { };
function request(url, options) {
options || (options = { });
var method = options.method ? options.method.toUpperCase() : 'GET',
onComplete = options.onComplete || function() { },
request = makeXHR(),
body;
request.onreadystatechange = function() {
if (request.readyState === 4) {
onComplete(request);
request.onreadystatechange = emptyFn;
}
};
if (method === 'GET') {
body = null;
if (typeof options.parameters == 'string') {
url = addParamToUrl(url, options.parameters);
}
}
request.open(method, url, true);
if (method === 'POST' || method === 'PUT') {
request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
}
request.send(body);
return request;
};
Canvas.base.request = request;
})();

View file

@ -255,7 +255,7 @@
* @param {HTMLImageElement|String} el The element representing the image
*/
_initElement: function(element) {
this.setElement($(element));
this.setElement(Canvas.base.getById(element));
Canvas.base.addClass(this.getElement(), Canvas.Image.CSS_CANVAS);
},

View file

@ -260,7 +260,7 @@
function parseElements(elements, options) {
// transform svg elements to Canvas.Path elements
var _elements = elements.map(function(el) {
var klass = Canvas[el.tagName.capitalize()];
var klass = Canvas[Canvas.base.string.capitalize(el.tagName)];
if (klass && klass.fromElement) {
try {
return klass.fromElement(el, options);
@ -346,7 +346,7 @@
height: height
};
var elements = Canvas.parseElements(elements, Object.clone(options));
var elements = Canvas.parseElements(elements, Canvas.base.object.clone(options));
if (!elements || (elements && !elements.length)) return;
if (callback) {

View file

@ -36,7 +36,8 @@
throw Error('`path` argument is required');
}
var fromArray = Object.isArray(path);
var fromArray = Object.prototype.toString.call(path) === '[object Array]';
this.path = fromArray
? path
: path.match && path.match(/[a-zA-Z][^a-zA-Z]*/g);

View file

@ -6,7 +6,7 @@
<title>Canvas demo</title>
<!--[if IE]>
<!--[if lt IE 9]>
<script src="js/core/excanvas.js" type="text/javascript"></script>
<![endif]-->
@ -14,11 +14,11 @@
<style type="text/css">
canvas { border: 1px solid #aaa; }
.canvas_container { margin: 0 auto; position: relative; }
</style>
</head>
<body>
<h2>Canvas demo</h2>
<script src="demo.js" type="text/javascript"></script>
</body>
</html>

View file

@ -22,11 +22,31 @@
left: 70,
top: 120
});
var ellipse = new Canvas.Ellipse({
fill: 'blue',
rx: 40,
ry: 20,
left: 150,
top: 145,
opacity: 0.5,
angle: 15
});
Canvas.Image.fromURL('http://www.google.com/intl/en_ALL/images/srpr/logo1w.png', function(image) {
image.set('left', 300).set('top', 500).set('angle', -25).setCoords();
canvas.add(image);
});
Canvas.Image.fromURL('http://www.dooziedog.com/dog_breeds/pug/images/full/Pug-Puppy.jpg', function(image) {
image.set('left', 450).set('top', 150).set('angle', -5).scale(0.3).setCoords();
canvas.add(image);
});
canvas.add(rect).add(circle);
canvas.add(rect).add(circle).add(ellipse.scale(2));
function loadSVGFromURL(url, callback) {
var r = new Ajax.Request(url, {
var req = new Canvas.base.request(url, {
method: 'get',
onComplete: function(r) {
var xml = r.responseXML;
@ -38,33 +58,31 @@
})
}
/*loadSVGFromURL('assets/1.svg', function(objects) {
loadSVGFromURL('assets/1.svg', function(objects) {
var o = objects[0];
o.set('left', 250).set('top', 300).setCoords();
canvas.add(o)
});
loadSVGFromURL('assets/2.svg', function(objects) {
var o = objects[0];
o.set('left', 350).set('top', 80).setCoords();
o.set('left', 650).set('top', 380).setCoords();
canvas.add(o)
});
/*
loadSVGFromURL('assets/3.svg', function(objects, options) {
var pathGroup = new Canvas.PathGroup(objects, options);
pathGroup.set('left', 550).set('top', 300).set('angle', 20).setCoords();
canvas.add(pathGroup);
});*/
Canvas.Image.fromURL('http://www.google.com/intl/en_ALL/images/srpr/logo1w.png', function(image) {
image.set('left', 300).set('top', 500).set('angle', -25).setCoords();
canvas.add(image);
});
/*loadSVGFromURL('assets/5.svg', function(objects, options) {
loadSVGFromURL('assets/5.svg', function(objects, options) {
var pathGroup = new Canvas.PathGroup(objects, options);
pathGroup.set('left', 800).set('top', 200).set('angle', -3).setCoords();
canvas.add(pathGroup);
});*/
});
*/
})();