Merge pull request #28 from gwwar/master

Setup travis, add testharness and debug playground, and fix regression for __createElement refactor
This commit is contained in:
clintjd 2015-06-18 17:02:18 -07:00
commit ff0fcb3f00
36 changed files with 7692 additions and 3623 deletions

4
.gitignore vendored
View File

@ -1 +1,3 @@
.idea/ .idea/
.node_modules/
node_modules/

6
.travis.yml Normal file
View File

@ -0,0 +1,6 @@
language: node_js
node_js:
- "0.10"
before_script:
- export DISPLAY=:99.0
- sh -e /etc/init.d/xvfb start

View File

@ -1,6 +1,7 @@
Canvas2Svg Canvas2Svg [![Build Status](https://travis-ci.org/gwwar/canvas2svg.svg?branch=master)](https://travis-ci.org/gwwar/canvas2svg)
========== ==========
This library turns your Canvas into SVG using javascript. In other words, this library lets you build an SVG document using the canvas api. Why use it? This library turns your Canvas into SVG using javascript. In other words, this library lets you build an SVG document
using the canvas api. Why use it?
* You have a canvas drawing you want to persist as an SVG file. * You have a canvas drawing you want to persist as an SVG file.
* You like exporting things. * You like exporting things.
* Because you didn't want to transform your custom file format to SVG. * Because you didn't want to transform your custom file format to SVG.
@ -11,7 +12,8 @@ http://gliffy.github.io/canvas2svg/
How it works How it works
========== ==========
We create a mock 2d canvas context. Use the canvas context like you would on a normal canvas. As you call methods, we build up a scene graph in SVG. Yay! We create a mock 2d canvas context. Use the canvas context like you would on a normal canvas. As you call methods, we
build up a scene graph in SVG. Yay!
Usage Usage
========== ==========
@ -31,8 +33,56 @@ var mySerializedSVG = ctx.getSerializedSvg(); //true here, if you need to conver
var svg = ctx.getSvg(); var svg = ctx.getSvg();
``` ```
Tests
==========
To run tests:
```
npm install
npm test
```
To run tests against Chrome and Firefox, call karma directly. This is not the default npm test due to the limited
browser selection in travis.
```
npm install karma-cli -g
karma start
```
Debug
=========
Play with canvas2svg in the provided test/playground.html or run test locally in your browser in test/testrunner.html
Add An Example Case
=========
Add a test file to the test/example folder. In your file make sure to add the drawing function to the global `C2S_EXAMPLES`,
with your filename as a key. For example `test\example\linewidth.js` should look something like:
```javascript
window.C2S_EXAMPLES['linewidth'] = function(ctx) {
for (var i = 0; i < 10; i++){
ctx.lineWidth = 1+i;
ctx.beginPath();
ctx.moveTo(5+i*14,5);
ctx.lineTo(5+i*14,140);
ctx.stroke();
}
};
```
install gulp globally if you haven't done so already
```
npm install -g gulp
```
Then run the following to update playground.html and testrunner.html
```
gulp
```
You should now be able to select your new example from playground.html or see it run in testrunner.html
If you find a bug, or want to add functionality, please add a new test case and include it with your pull request.
Updates Updates
========== ==========
- v1.0.14 bugfix for gradients, move __createElement to scoped createElement function, so all classes have access.
- v1.0.13 set paint order before stroke and fill to make them behavior like canvas - v1.0.13 set paint order before stroke and fill to make them behavior like canvas
- v1.0.12 Implementation of ctx.prototype.arcTo. - v1.0.12 Implementation of ctx.prototype.arcTo.
- v1.0.11 call lineTo instead moveTo in ctx.arc, fixes closePath issue and straight line issue - v1.0.11 call lineTo instead moveTo in ctx.arc, fixes closePath issue and straight line issue

View File

@ -1,5 +1,5 @@
/*!! /*!!
* Canvas 2 Svg v1.0.13 * Canvas 2 Svg v1.0.14
* A low level canvas to SVG converter. Uses a mock canvas context to build an SVG document. * A low level canvas to SVG converter. Uses a mock canvas context to build an SVG document.
* *
* Licensed under the MIT license: * Licensed under the MIT license:
@ -72,6 +72,29 @@
return mapping[textBaseline] || mapping.alphabetic; return mapping[textBaseline] || mapping.alphabetic;
} }
/**
* Creates the specified svg element
* @private
*/
function createElement(elementName, properties, resetFill) {
if (typeof properties === "undefined") {
properties = {};
}
var element = document.createElementNS("http://www.w3.org/2000/svg", elementName),
keys = Object.keys(properties), i, key;
if(resetFill) {
//if fill or stroke is not specified, the svg element should not display. By default SVG's fill is black.
element.setAttribute("fill", "none");
element.setAttribute("stroke", "none");
}
for(i=0; i<keys.length; i++) {
key = keys[i];
element.setAttribute(key, properties[key]);
}
return element;
}
// Unpack entities lookup where the numbers are in radix 32 to reduce the size // Unpack entities lookup where the numbers are in radix 32 to reduce the size
// entity mapping courtesy of tinymce // entity mapping courtesy of tinymce
namedEntities = createNamedToNumberedLookup( namedEntities = createNamedToNumberedLookup(
@ -183,7 +206,7 @@
* Adds a color stop to the gradient root * Adds a color stop to the gradient root
*/ */
CanvasGradient.prototype.addColorStop = function(offset, color) { CanvasGradient.prototype.addColorStop = function(offset, color) {
var stop = this.__createElement("stop"), regex, matches; var stop = createElement("stop"), regex, matches;
stop.setAttribute("offset", offset); stop.setAttribute("offset", offset);
if(color.indexOf("rgba") !== -1) { if(color.indexOf("rgba") !== -1) {
//separate alpha value, since webkit can't handle it //separate alpha value, since webkit can't handle it
@ -262,29 +285,6 @@
this.__root.appendChild(this.__currentElement); this.__root.appendChild(this.__currentElement);
}; };
/**
* Creates the specified svg element
* @private
*/
ctx.prototype.__createElement = function(elementName, properties, resetFill) {
if (typeof properties === "undefined") {
properties = {};
}
var element = document.createElementNS("http://www.w3.org/2000/svg", elementName),
keys = Object.keys(properties), i, key;
if(resetFill) {
//if fill or stroke is not specified, the svg element should not display. By default SVG's fill is black.
element.setAttribute("fill", "none");
element.setAttribute("stroke", "none");
}
for(i=0; i<keys.length; i++) {
key = keys[i];
element.setAttribute(key, properties[key]);
}
return element;
};
/** /**
* Applies default canvas styles to the context * Applies default canvas styles to the context
* @private * @private
@ -426,7 +426,7 @@
* Will generate a group tag. * Will generate a group tag.
*/ */
ctx.prototype.save = function() { ctx.prototype.save = function() {
var group = this.__createElement("g"), parent = this.__closestGroupOrSvg(); var group = createElement("g"), parent = this.__closestGroupOrSvg();
this.__groupStack.push(parent); this.__groupStack.push(parent);
parent.appendChild(group); parent.appendChild(group);
this.__currentElement = group; this.__currentElement = group;
@ -451,7 +451,7 @@
//if the current element has siblings, add another group //if the current element has siblings, add another group
var parent = this.__closestGroupOrSvg(); var parent = this.__closestGroupOrSvg();
if(parent.childNodes.length > 0) { if(parent.childNodes.length > 0) {
var group = this.__createElement("g"); var group = createElement("g");
parent.appendChild(group); parent.appendChild(group);
this.__currentElement = group; this.__currentElement = group;
} }
@ -509,7 +509,7 @@
this.__currentDefaultPath = ""; this.__currentDefaultPath = "";
this.__currentPosition = {}; this.__currentPosition = {};
path = this.__createElement("path", {}, true); path = createElement("path", {}, true);
parent = this.__closestGroupOrSvg(); parent = this.__closestGroupOrSvg();
parent.appendChild(path); parent.appendChild(path);
this.__currentElement = path; this.__currentElement = path;
@ -732,7 +732,7 @@
*/ */
ctx.prototype.fillRect = function(x, y, width, height){ ctx.prototype.fillRect = function(x, y, width, height){
var rect, parent; var rect, parent;
rect = this.__createElement("rect", { rect = createElement("rect", {
x : x, x : x,
y : y, y : y,
width : width, width : width,
@ -753,7 +753,7 @@
*/ */
ctx.prototype.strokeRect = function(x, y, width, height){ ctx.prototype.strokeRect = function(x, y, width, height){
var rect, parent; var rect, parent;
rect = this.__createElement("rect", { rect = createElement("rect", {
x : x, x : x,
y : y, y : y,
width : width, width : width,
@ -771,7 +771,7 @@
*/ */
ctx.prototype.clearRect = function(x, y, width, height) { ctx.prototype.clearRect = function(x, y, width, height) {
var rect, parent = this.__closestGroupOrSvg(); var rect, parent = this.__closestGroupOrSvg();
rect = this.__createElement("rect", { rect = createElement("rect", {
x : x, x : x,
y : y, y : y,
width : width, width : width,
@ -786,7 +786,7 @@
* Returns a canvas gradient object that has a reference to it's parent def * Returns a canvas gradient object that has a reference to it's parent def
*/ */
ctx.prototype.createLinearGradient = function(x1, y1, x2, y2){ ctx.prototype.createLinearGradient = function(x1, y1, x2, y2){
var grad = this.__createElement("linearGradient", { var grad = createElement("linearGradient", {
id : randomString(this.__ids), id : randomString(this.__ids),
x1 : x1+"px", x1 : x1+"px",
x2 : x2+"px", x2 : x2+"px",
@ -803,7 +803,7 @@
* Returns a canvas gradient object that has a reference to it's parent def * Returns a canvas gradient object that has a reference to it's parent def
*/ */
ctx.prototype.createRadialGradient = function(x0, y0, r0, x1, y1, r1){ ctx.prototype.createRadialGradient = function(x0, y0, r0, x1, y1, r1){
var grad = this.__createElement("radialGradient", { var grad = createElement("radialGradient", {
id : randomString(this.__ids), id : randomString(this.__ids),
cx : x1+"px", cx : x1+"px",
cy : y1+"px", cy : y1+"px",
@ -855,7 +855,7 @@
*/ */
ctx.prototype.__wrapTextLink = function(font, element) { ctx.prototype.__wrapTextLink = function(font, element) {
if(font.href) { if(font.href) {
var a = this.__createElement("a"); var a = createElement("a");
a.setAttributeNS("http://www.w3.org/1999/xlink", "xlink:href", font.href); a.setAttributeNS("http://www.w3.org/1999/xlink", "xlink:href", font.href);
a.appendChild(element); a.appendChild(element);
return a; return a;
@ -874,7 +874,7 @@
ctx.prototype.__applyText = function(text, x, y, action) { ctx.prototype.__applyText = function(text, x, y, action) {
var font = this.__parseFont(), var font = this.__parseFont(),
parent = this.__closestGroupOrSvg(), parent = this.__closestGroupOrSvg(),
textElement = this.__createElement("text", { textElement = createElement("text", {
"font-family" : font.family, "font-family" : font.family,
"font-size" : font.size, "font-size" : font.size,
"font-style" : font.style, "font-style" : font.style,
@ -963,9 +963,9 @@
*/ */
ctx.prototype.clip = function(){ ctx.prototype.clip = function(){
var group = this.__closestGroupOrSvg(), var group = this.__closestGroupOrSvg(),
clipPath = this.__createElement("clipPath"), clipPath = createElement("clipPath"),
id = randomString(this.__ids), id = randomString(this.__ids),
newGroup = this.__createElement("g"); newGroup = createElement("g");
group.removeChild(this.__currentElement); group.removeChild(this.__currentElement);
clipPath.setAttribute("id", id); clipPath.setAttribute("id", id);
@ -1043,7 +1043,7 @@
this.__currentElement = currentElement; this.__currentElement = currentElement;
} else if(image.nodeName === "CANVAS" || image.nodeName === "IMG") { } else if(image.nodeName === "CANVAS" || image.nodeName === "IMG") {
//canvas or image //canvas or image
svgImage = this.__createElement("image"); svgImage = createElement("image");
svgImage.setAttribute("width", dw); svgImage.setAttribute("width", dw);
svgImage.setAttribute("height", dh); svgImage.setAttribute("height", dh);
svgImage.setAttribute("preserveAspectRatio", "none"); svgImage.setAttribute("preserveAspectRatio", "none");

31
gulpfile.js Normal file
View File

@ -0,0 +1,31 @@
"use strict";
var gulp = require('gulp');
var fs = require('fs');
var path = require('path');
var cheerio = require('cheerio');
function updateExample(filename) {
var playground = fs.readFileSync(path.join(__dirname, filename), {'encoding': 'utf8'});
var filenames = fs.readdirSync(path.join(__dirname,'test/example'));
var $ = cheerio.load(playground);
var $examples = $('#examples');
var $select = $('#select');
$examples.empty();
$select.empty();
filenames.forEach(function(filename) {
var name = filename.replace('.js', '');
$examples.append($('<script type="text/javascript" src="example/'+filename+'"></script>'));
$select.append($('<option value="'+name+'">'+name+'</option>'));
});
fs.writeFileSync(path.join(__dirname, filename), $.html(), {'encoding': 'utf8'})
}
// run this after adding an example file to update playground.html, and testrunner.html
gulp.task('update_examples', function() {
updateExample('test/playground.html');
updateExample('test/testrunner.html');
});
gulp.task('default', ['update_examples']);

View File

@ -1,24 +0,0 @@
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Jasmine Spec Runner v2.0.0</title>
<link rel="shortcut icon" type="image/png" href="lib/jasmine-2.0.0/jasmine_favicon.png">
<link rel="stylesheet" type="text/css" href="lib/jasmine-2.0.0/jasmine.css">
<script type="text/javascript" src="lib/jasmine-2.0.0/jasmine.js"></script>
<script type="text/javascript" src="lib/jasmine-2.0.0/jasmine-html.js"></script>
<script type="text/javascript" src="lib/jasmine-2.0.0/boot.js"></script>
<!-- include source files here... -->
<script type="text/javascript" src="../canvas2svg.js"></script>
<!-- include spec files here... -->
<script type="text/javascript" src="spec/canvas2svgspec.js"></script>
</head>
<body>
</body>
</html>

View File

@ -1,57 +0,0 @@
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Canvas2Svg</title>
<script type="text/javascript" src="../canvas2svg.js"></script>
<style type="text/css">
canvas {
float:left;
}
#svg {
width: 500px;
height: 500px;
float: left;
}
textarea {
width:500px;
height:100px;
}
</style>
</head>
<body>
<div id="container">
<canvas id="canvas" width="500" height="500"></canvas>
<div id="svg">
</div>
<textarea id="textarea">
</textarea>
<a href="#" id="render">Render</a>
</div>
<script type="text/javascript">
(function() {
"use strict";
document.getElementById("render").addEventListener("click", function(event){
event.preventDefault();
var ctx = document.getElementById("canvas").getContext("2d");
ctx.clearRect(0,0,500,500);
var c2s = new C2S(500,500);
var text = document.getElementById("textarea").value;
var drawFunction = new Function("ctx", text);
var svg = document.getElementById("svg");
drawFunction(ctx);
drawFunction(c2s);
if(svg.children.length>0) {
svg.removeChild(svg.children[0]);
}
svg.appendChild(c2s.getSvg());
} , false);
}());
</script>
</body>
</html>

View File

@ -1,181 +0,0 @@
/**
Starting with version 2.0, this file "boots" Jasmine, performing all of the necessary initialization before executing the loaded environment and all of a project's specs. This file should be loaded after `jasmine.js`, but before any project source files or spec files are loaded. Thus this file can also be used to customize Jasmine for a project.
If a project is using Jasmine via the standalone distribution, this file can be customized directly. If a project is using Jasmine via the [Ruby gem][jasmine-gem], this file can be copied into the support directory via `jasmine copy_boot_js`. Other environments (e.g., Python) will have different mechanisms.
The location of `boot.js` can be specified and/or overridden in `jasmine.yml`.
[jasmine-gem]: http://github.com/pivotal/jasmine-gem
*/
(function() {
/**
* ## Require &amp; Instantiate
*
* Require Jasmine's core files. Specifically, this requires and attaches all of Jasmine's code to the `jasmine` reference.
*/
window.jasmine = jasmineRequire.core(jasmineRequire);
/**
* Since this is being run in a browser and the results should populate to an HTML page, require the HTML-specific Jasmine code, injecting the same reference.
*/
jasmineRequire.html(jasmine);
/**
* Create the Jasmine environment. This is used to run all specs in a project.
*/
var env = jasmine.getEnv();
/**
* ## The Global Interface
*
* Build up the functions that will be exposed as the Jasmine public interface. A project can customize, rename or alias any of these functions as desired, provided the implementation remains unchanged.
*/
var jasmineInterface = {
describe: function(description, specDefinitions) {
return env.describe(description, specDefinitions);
},
xdescribe: function(description, specDefinitions) {
return env.xdescribe(description, specDefinitions);
},
it: function(desc, func) {
return env.it(desc, func);
},
xit: function(desc, func) {
return env.xit(desc, func);
},
beforeEach: function(beforeEachFunction) {
return env.beforeEach(beforeEachFunction);
},
afterEach: function(afterEachFunction) {
return env.afterEach(afterEachFunction);
},
expect: function(actual) {
return env.expect(actual);
},
pending: function() {
return env.pending();
},
spyOn: function(obj, methodName) {
return env.spyOn(obj, methodName);
},
jsApiReporter: new jasmine.JsApiReporter({
timer: new jasmine.Timer()
})
};
/**
* Add all of the Jasmine global/public interface to the proper global, so a project can use the public interface directly. For example, calling `describe` in specs instead of `jasmine.getEnv().describe`.
*/
if (typeof window == "undefined" && typeof exports == "object") {
extend(exports, jasmineInterface);
} else {
extend(window, jasmineInterface);
}
/**
* Expose the interface for adding custom equality testers.
*/
jasmine.addCustomEqualityTester = function(tester) {
env.addCustomEqualityTester(tester);
};
/**
* Expose the interface for adding custom expectation matchers
*/
jasmine.addMatchers = function(matchers) {
return env.addMatchers(matchers);
};
/**
* Expose the mock interface for the JavaScript timeout functions
*/
jasmine.clock = function() {
return env.clock;
};
/**
* ## Runner Parameters
*
* More browser specific code - wrap the query string in an object and to allow for getting/setting parameters from the runner user interface.
*/
var queryString = new jasmine.QueryString({
getWindowLocation: function() { return window.location; }
});
var catchingExceptions = queryString.getParam("catch");
env.catchExceptions(typeof catchingExceptions === "undefined" ? true : catchingExceptions);
/**
* ## Reporters
* The `HtmlReporter` builds all of the HTML UI for the runner page. This reporter paints the dots, stars, and x's for specs, as well as all spec names and all failures (if any).
*/
var htmlReporter = new jasmine.HtmlReporter({
env: env,
onRaiseExceptionsClick: function() { queryString.setParam("catch", !env.catchingExceptions()); },
getContainer: function() { return document.body; },
createElement: function() { return document.createElement.apply(document, arguments); },
createTextNode: function() { return document.createTextNode.apply(document, arguments); },
timer: new jasmine.Timer()
});
/**
* The `jsApiReporter` also receives spec results, and is used by any environment that needs to extract the results from JavaScript.
*/
env.addReporter(jasmineInterface.jsApiReporter);
env.addReporter(htmlReporter);
/**
* Filter which specs will be run by matching the start of the full name against the `spec` query param.
*/
var specFilter = new jasmine.HtmlSpecFilter({
filterString: function() { return queryString.getParam("spec"); }
});
env.specFilter = function(spec) {
return specFilter.matches(spec.getFullName());
};
/**
* Setting up timing functions to be able to be overridden. Certain browsers (Safari, IE 8, phantomjs) require this hack.
*/
window.setTimeout = window.setTimeout;
window.setInterval = window.setInterval;
window.clearTimeout = window.clearTimeout;
window.clearInterval = window.clearInterval;
/**
* ## Execution
*
* Replace the browser window's `onload`, ensure it's called, and then run all of the loaded specs. This includes initializing the `HtmlReporter` instance and then executing the loaded Jasmine environment. All of this will happen after all of the specs are loaded.
*/
var currentWindowOnload = window.onload;
window.onload = function() {
if (currentWindowOnload) {
currentWindowOnload();
}
htmlReporter.initialize();
env.execute();
};
/**
* Helper function for readability above.
*/
function extend(destination, source) {
for (var property in source) destination[property] = source[property];
return destination;
}
}());

View File

@ -1,160 +0,0 @@
/*
Copyright (c) 2008-2013 Pivotal Labs
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
function getJasmineRequireObj() {
if (typeof module !== "undefined" && module.exports) {
return exports;
} else {
window.jasmineRequire = window.jasmineRequire || {};
return window.jasmineRequire;
}
}
getJasmineRequireObj().console = function(jRequire, j$) {
j$.ConsoleReporter = jRequire.ConsoleReporter();
};
getJasmineRequireObj().ConsoleReporter = function() {
var noopTimer = {
start: function(){},
elapsed: function(){ return 0; }
};
function ConsoleReporter(options) {
var print = options.print,
showColors = options.showColors || false,
onComplete = options.onComplete || function() {},
timer = options.timer || noopTimer,
specCount,
failureCount,
failedSpecs = [],
pendingCount,
ansi = {
green: '\x1B[32m',
red: '\x1B[31m',
yellow: '\x1B[33m',
none: '\x1B[0m'
};
this.jasmineStarted = function() {
specCount = 0;
failureCount = 0;
pendingCount = 0;
print("Started");
printNewline();
timer.start();
};
this.jasmineDone = function() {
printNewline();
for (var i = 0; i < failedSpecs.length; i++) {
specFailureDetails(failedSpecs[i]);
}
printNewline();
var specCounts = specCount + " " + plural("spec", specCount) + ", " +
failureCount + " " + plural("failure", failureCount);
if (pendingCount) {
specCounts += ", " + pendingCount + " pending " + plural("spec", pendingCount);
}
print(specCounts);
printNewline();
var seconds = timer.elapsed() / 1000;
print("Finished in " + seconds + " " + plural("second", seconds));
printNewline();
onComplete(failureCount === 0);
};
this.specDone = function(result) {
specCount++;
if (result.status == "pending") {
pendingCount++;
print(colored("yellow", "*"));
return;
}
if (result.status == "passed") {
print(colored("green", '.'));
return;
}
if (result.status == "failed") {
failureCount++;
failedSpecs.push(result);
print(colored("red", 'F'));
}
};
return this;
function printNewline() {
print("\n");
}
function colored(color, str) {
return showColors ? (ansi[color] + str + ansi.none) : str;
}
function plural(str, count) {
return count == 1 ? str : str + "s";
}
function repeat(thing, times) {
var arr = [];
for (var i = 0; i < times; i++) {
arr.push(thing);
}
return arr;
}
function indent(str, spaces) {
var lines = (str || '').split("\n");
var newArr = [];
for (var i = 0; i < lines.length; i++) {
newArr.push(repeat(" ", spaces).join("") + lines[i]);
}
return newArr.join("\n");
}
function specFailureDetails(result) {
printNewline();
print(result.fullName);
for (var i = 0; i < result.failedExpectations.length; i++) {
var failedExpectation = result.failedExpectations[i];
printNewline();
print(indent(failedExpectation.stack, 2));
}
printNewline();
}
}
return ConsoleReporter;
};

View File

@ -1,359 +0,0 @@
/*
Copyright (c) 2008-2013 Pivotal Labs
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
jasmineRequire.html = function(j$) {
j$.ResultsNode = jasmineRequire.ResultsNode();
j$.HtmlReporter = jasmineRequire.HtmlReporter(j$);
j$.QueryString = jasmineRequire.QueryString();
j$.HtmlSpecFilter = jasmineRequire.HtmlSpecFilter();
};
jasmineRequire.HtmlReporter = function(j$) {
var noopTimer = {
start: function() {},
elapsed: function() { return 0; }
};
function HtmlReporter(options) {
var env = options.env || {},
getContainer = options.getContainer,
createElement = options.createElement,
createTextNode = options.createTextNode,
onRaiseExceptionsClick = options.onRaiseExceptionsClick || function() {},
timer = options.timer || noopTimer,
results = [],
specsExecuted = 0,
failureCount = 0,
pendingSpecCount = 0,
htmlReporterMain,
symbols;
this.initialize = function() {
htmlReporterMain = createDom("div", {className: "html-reporter"},
createDom("div", {className: "banner"},
createDom("span", {className: "title"}, "Jasmine"),
createDom("span", {className: "version"}, j$.version)
),
createDom("ul", {className: "symbol-summary"}),
createDom("div", {className: "alert"}),
createDom("div", {className: "results"},
createDom("div", {className: "failures"})
)
);
getContainer().appendChild(htmlReporterMain);
symbols = find(".symbol-summary");
};
var totalSpecsDefined;
this.jasmineStarted = function(options) {
totalSpecsDefined = options.totalSpecsDefined || 0;
timer.start();
};
var summary = createDom("div", {className: "summary"});
var topResults = new j$.ResultsNode({}, "", null),
currentParent = topResults;
this.suiteStarted = function(result) {
currentParent.addChild(result, "suite");
currentParent = currentParent.last();
};
this.suiteDone = function(result) {
if (currentParent == topResults) {
return;
}
currentParent = currentParent.parent;
};
this.specStarted = function(result) {
currentParent.addChild(result, "spec");
};
var failures = [];
this.specDone = function(result) {
if (result.status != "disabled") {
specsExecuted++;
}
symbols.appendChild(createDom("li", {
className: result.status,
id: "spec_" + result.id,
title: result.fullName
}
));
if (result.status == "failed") {
failureCount++;
var failure =
createDom("div", {className: "spec-detail failed"},
createDom("div", {className: "description"},
createDom("a", {title: result.fullName, href: specHref(result)}, result.fullName)
),
createDom("div", {className: "messages"})
);
var messages = failure.childNodes[1];
for (var i = 0; i < result.failedExpectations.length; i++) {
var expectation = result.failedExpectations[i];
messages.appendChild(createDom("div", {className: "result-message"}, expectation.message));
messages.appendChild(createDom("div", {className: "stack-trace"}, expectation.stack));
}
failures.push(failure);
}
if (result.status == "pending") {
pendingSpecCount++;
}
};
this.jasmineDone = function() {
var banner = find(".banner");
banner.appendChild(createDom("span", {className: "duration"}, "finished in " + timer.elapsed() / 1000 + "s"));
var alert = find(".alert");
alert.appendChild(createDom("span", { className: "exceptions" },
createDom("label", { className: "label", 'for': "raise-exceptions" }, "raise exceptions"),
createDom("input", {
className: "raise",
id: "raise-exceptions",
type: "checkbox"
})
));
var checkbox = find("input");
checkbox.checked = !env.catchingExceptions();
checkbox.onclick = onRaiseExceptionsClick;
if (specsExecuted < totalSpecsDefined) {
var skippedMessage = "Ran " + specsExecuted + " of " + totalSpecsDefined + " specs - run all";
alert.appendChild(
createDom("span", {className: "bar skipped"},
createDom("a", {href: "?", title: "Run all specs"}, skippedMessage)
)
);
}
var statusBarMessage = "" + pluralize("spec", specsExecuted) + ", " + pluralize("failure", failureCount);
if (pendingSpecCount) { statusBarMessage += ", " + pluralize("pending spec", pendingSpecCount); }
var statusBarClassName = "bar " + ((failureCount > 0) ? "failed" : "passed");
alert.appendChild(createDom("span", {className: statusBarClassName}, statusBarMessage));
var results = find(".results");
results.appendChild(summary);
summaryList(topResults, summary);
function summaryList(resultsTree, domParent) {
var specListNode;
for (var i = 0; i < resultsTree.children.length; i++) {
var resultNode = resultsTree.children[i];
if (resultNode.type == "suite") {
var suiteListNode = createDom("ul", {className: "suite", id: "suite-" + resultNode.result.id},
createDom("li", {className: "suite-detail"},
createDom("a", {href: specHref(resultNode.result)}, resultNode.result.description)
)
);
summaryList(resultNode, suiteListNode);
domParent.appendChild(suiteListNode);
}
if (resultNode.type == "spec") {
if (domParent.getAttribute("class") != "specs") {
specListNode = createDom("ul", {className: "specs"});
domParent.appendChild(specListNode);
}
specListNode.appendChild(
createDom("li", {
className: resultNode.result.status,
id: "spec-" + resultNode.result.id
},
createDom("a", {href: specHref(resultNode.result)}, resultNode.result.description)
)
);
}
}
}
if (failures.length) {
alert.appendChild(
createDom('span', {className: "menu bar spec-list"},
createDom("span", {}, "Spec List | "),
createDom('a', {className: "failures-menu", href: "#"}, "Failures")));
alert.appendChild(
createDom('span', {className: "menu bar failure-list"},
createDom('a', {className: "spec-list-menu", href: "#"}, "Spec List"),
createDom("span", {}, " | Failures ")));
find(".failures-menu").onclick = function() {
setMenuModeTo('failure-list');
};
find(".spec-list-menu").onclick = function() {
setMenuModeTo('spec-list');
};
setMenuModeTo('failure-list');
var failureNode = find(".failures");
for (var i = 0; i < failures.length; i++) {
failureNode.appendChild(failures[i]);
}
}
};
return this;
function find(selector) {
return getContainer().querySelector(selector);
}
function createDom(type, attrs, childrenVarArgs) {
var el = createElement(type);
for (var i = 2; i < arguments.length; i++) {
var child = arguments[i];
if (typeof child === 'string') {
el.appendChild(createTextNode(child));
} else {
if (child) {
el.appendChild(child);
}
}
}
for (var attr in attrs) {
if (attr == "className") {
el[attr] = attrs[attr];
} else {
el.setAttribute(attr, attrs[attr]);
}
}
return el;
}
function pluralize(singular, count) {
var word = (count == 1 ? singular : singular + "s");
return "" + count + " " + word;
}
function specHref(result) {
return "?spec=" + encodeURIComponent(result.fullName);
}
function setMenuModeTo(mode) {
htmlReporterMain.setAttribute("class", "html-reporter " + mode);
}
}
return HtmlReporter;
};
jasmineRequire.HtmlSpecFilter = function() {
function HtmlSpecFilter(options) {
var filterString = options && options.filterString() && options.filterString().replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
var filterPattern = new RegExp(filterString);
this.matches = function(specName) {
return filterPattern.test(specName);
};
}
return HtmlSpecFilter;
};
jasmineRequire.ResultsNode = function() {
function ResultsNode(result, type, parent) {
this.result = result;
this.type = type;
this.parent = parent;
this.children = [];
this.addChild = function(result, type) {
this.children.push(new ResultsNode(result, type, this));
};
this.last = function() {
return this.children[this.children.length - 1];
};
}
return ResultsNode;
};
jasmineRequire.QueryString = function() {
function QueryString(options) {
this.setParam = function(key, value) {
var paramMap = queryStringToParamMap();
paramMap[key] = value;
options.getWindowLocation().search = toQueryString(paramMap);
};
this.getParam = function(key) {
return queryStringToParamMap()[key];
};
return this;
function toQueryString(paramMap) {
var qStrPairs = [];
for (var prop in paramMap) {
qStrPairs.push(encodeURIComponent(prop) + "=" + encodeURIComponent(paramMap[prop]));
}
return "?" + qStrPairs.join('&');
}
function queryStringToParamMap() {
var paramStr = options.getWindowLocation().search.substring(1),
params = [],
paramMap = {};
if (paramStr.length > 0) {
params = paramStr.split('&');
for (var i = 0; i < params.length; i++) {
var p = params[i].split('=');
var value = decodeURIComponent(p[1]);
if (value === "true" || value === "false") {
value = JSON.parse(value);
}
paramMap[decodeURIComponent(p[0])] = value;
}
}
return paramMap;
}
}
return QueryString;
};

View File

@ -1,55 +0,0 @@
body { background-color: #eeeeee; padding: 0; margin: 5px; overflow-y: scroll; }
.html-reporter { font-size: 11px; font-family: Monaco, "Lucida Console", monospace; line-height: 14px; color: #333333; }
.html-reporter a { text-decoration: none; }
.html-reporter a:hover { text-decoration: underline; }
.html-reporter p, .html-reporter h1, .html-reporter h2, .html-reporter h3, .html-reporter h4, .html-reporter h5, .html-reporter h6 { margin: 0; line-height: 14px; }
.html-reporter .banner, .html-reporter .symbol-summary, .html-reporter .summary, .html-reporter .result-message, .html-reporter .spec .description, .html-reporter .spec-detail .description, .html-reporter .alert .bar, .html-reporter .stack-trace { padding-left: 9px; padding-right: 9px; }
.html-reporter .banner .version { margin-left: 14px; }
.html-reporter #jasmine_content { position: fixed; right: 100%; }
.html-reporter .version { color: #aaaaaa; }
.html-reporter .banner { margin-top: 14px; }
.html-reporter .duration { color: #aaaaaa; float: right; }
.html-reporter .symbol-summary { overflow: hidden; *zoom: 1; margin: 14px 0; }
.html-reporter .symbol-summary li { display: inline-block; height: 8px; width: 14px; font-size: 16px; }
.html-reporter .symbol-summary li.passed { font-size: 14px; }
.html-reporter .symbol-summary li.passed:before { color: #5e7d00; content: "\02022"; }
.html-reporter .symbol-summary li.failed { line-height: 9px; }
.html-reporter .symbol-summary li.failed:before { color: #b03911; content: "x"; font-weight: bold; margin-left: -1px; }
.html-reporter .symbol-summary li.disabled { font-size: 14px; }
.html-reporter .symbol-summary li.disabled:before { color: #bababa; content: "\02022"; }
.html-reporter .symbol-summary li.pending { line-height: 17px; }
.html-reporter .symbol-summary li.pending:before { color: #ba9d37; content: "*"; }
.html-reporter .exceptions { color: #fff; float: right; margin-top: 5px; margin-right: 5px; }
.html-reporter .bar { line-height: 28px; font-size: 14px; display: block; color: #eee; }
.html-reporter .bar.failed { background-color: #b03911; }
.html-reporter .bar.passed { background-color: #a6b779; }
.html-reporter .bar.skipped { background-color: #bababa; }
.html-reporter .bar.menu { background-color: #fff; color: #aaaaaa; }
.html-reporter .bar.menu a { color: #333333; }
.html-reporter .bar a { color: white; }
.html-reporter.spec-list .bar.menu.failure-list, .html-reporter.spec-list .results .failures { display: none; }
.html-reporter.failure-list .bar.menu.spec-list, .html-reporter.failure-list .summary { display: none; }
.html-reporter .running-alert { background-color: #666666; }
.html-reporter .results { margin-top: 14px; }
.html-reporter.showDetails .summaryMenuItem { font-weight: normal; text-decoration: inherit; }
.html-reporter.showDetails .summaryMenuItem:hover { text-decoration: underline; }
.html-reporter.showDetails .detailsMenuItem { font-weight: bold; text-decoration: underline; }
.html-reporter.showDetails .summary { display: none; }
.html-reporter.showDetails #details { display: block; }
.html-reporter .summaryMenuItem { font-weight: bold; text-decoration: underline; }
.html-reporter .summary { margin-top: 14px; }
.html-reporter .summary ul { list-style-type: none; margin-left: 14px; padding-top: 0; padding-left: 0; }
.html-reporter .summary ul.suite { margin-top: 7px; margin-bottom: 7px; }
.html-reporter .summary li.passed a { color: #5e7d00; }
.html-reporter .summary li.failed a { color: #b03911; }
.html-reporter .summary li.pending a { color: #ba9d37; }
.html-reporter .description + .suite { margin-top: 0; }
.html-reporter .suite { margin-top: 14px; }
.html-reporter .suite a { color: #333333; }
.html-reporter .failures .spec-detail { margin-bottom: 28px; }
.html-reporter .failures .spec-detail .description { background-color: #b03911; }
.html-reporter .failures .spec-detail .description a { color: white; }
.html-reporter .result-message { padding-top: 14px; color: #333333; white-space: pre; }
.html-reporter .result-message span.result { display: block; }
.html-reporter .stack-trace { margin: 5px 0 0 0; max-height: 224px; overflow: auto; line-height: 18px; color: #666666; border: 1px solid #ddd; background: white; white-space: pre; }

File diff suppressed because it is too large Load Diff

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.0 KiB

View File

@ -1,343 +0,0 @@
describe("canvas2svg", function() {
describe("can by created", function() {
it("with options", function() {
var ctx = new C2S({width:100, height:200, enableMirroring:true});
expect(ctx instanceof C2S).toBe(true);
expect(ctx.width).toEqual(100);
expect(ctx.height).toEqual(200);
expect(ctx.enableMirroring).toEqual(true);
var ctx2 = new C2S(300,400);
expect(ctx2 instanceof C2S).toBe(true);
expect(ctx2.width).toEqual(300);
expect(ctx2.height).toEqual(400);
expect(ctx2.enableMirroring).toEqual(false);
});
it("with no options and have defaults", function() {
var ctx = new C2S();
expect(ctx instanceof C2S).toBe(true);
expect(ctx.width).toEqual(500);
expect(ctx.height).toEqual(500);
expect(ctx.enableMirroring).toEqual(false);
});
it("even if it's called as a function", function() {
//notice the lack of new!
var ctx = C2S({width:100, height:200, enableMirroring:true});
expect(ctx instanceof C2S).toBe(true);
expect(ctx.width).toEqual(100);
expect(ctx.height).toEqual(200);
expect(ctx.enableMirroring).toEqual(true);
var ctx2 = C2S(300,400);
expect(ctx2 instanceof C2S).toBe(true);
expect(ctx2.width).toEqual(300);
expect(ctx2.height).toEqual(400);
expect(ctx2.enableMirroring).toEqual(false);
var ctx3 = C2S();
expect(ctx3 instanceof C2S).toBe(true);
expect(ctx3.width).toEqual(500);
expect(ctx3.height).toEqual(500);
expect(ctx3.enableMirroring).toEqual(false);
});
});
describe("has implemented methods", function() {
var ctx,
methods =
[
"save",
"restore",
"scale",
"rotate",
"translate",
"transform",
"beginPath",
"moveTo",
"closePath",
"lineTo",
"bezierCurveTo",
"quadraticCurveTo",
"stroke",
"fill",
"rect",
"fillRect",
"strokeRect",
"clearRect",
"createLinearGradient",
"createRadialGradient",
"fillText",
"strokeText",
"measureText",
"arc",
"clip",
"drawImage",
"createPattern"
];
beforeEach(function() {
ctx = new C2S();
});
//TODO: better tests for each method
for(var i=0; i<methods.length; i++) {
(function(j) {
it(methods[j], function(){
expect(ctx[""+methods[j]]).toBeDefined();
});
}(i));
}
});
describe("can export to", function() {
it("inline svg", function() {
var ctx = new C2S();
ctx.fillStyle="red";
ctx.fillRect(100,100,100,100);
//svg is of course not attached to the document
var svg = ctx.getSvg();
expect(svg.nodeType).toEqual(1);
expect(svg.nodeName).toEqual("svg");
});
it("serialized svg", function() {
var ctx = new C2S();
ctx.fillStyle="red";
ctx.fillRect(100,100,100,100);
//Standalone SVG doesn't support named entities, which document.createTextNode encodes.
//passing in true will attempt to find all named entities and encode it as a numeric entity.
var string = ctx.getSerializedSvg(true);
expect(typeof string).toBe("string");
expect(string).toEqual('<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="500" height="500"><defs/><g><rect fill="red" stroke="none" x="100" y="100" width="100" height="100"/></g></svg>');
});
});
describe("with multiple transforms and fill/strokes", function() {
it("creates new groups", function() {
var ctx = new C2S();
ctx.translate(0, 20);
ctx.fillRect(0, 0, 10, 10);
ctx.translate(10, 20);
ctx.fillRect(0, 0, 10, 10);
ctx.translate(20, 20);
ctx.fillRect(0, 0, 10, 10);
var svg = ctx.getSvg();
var firstGroup = svg.querySelector("g");
expect(firstGroup.getAttribute("transform")).toEqual("translate(0,20)");
var secondGroup = firstGroup.querySelector("g");
expect(secondGroup.getAttribute("transform")).toEqual("translate(10,20)");
var thirdGroup = secondGroup.querySelector("g");
expect(thirdGroup.getAttribute("transform")).toEqual("translate(20,20)");
});
it("save and restore still works", function() {
var ctx = new C2S();
ctx.translate(0, 10);
ctx.fillRect(0, 0, 10, 10);
ctx.save();
ctx.translate(40, 40);
ctx.fillRect(0, 0, 10, 10);
ctx.restore();
ctx.translate(0, 10);
ctx.fillRect(0, 0, 10, 10);
var svg = ctx.getSvg();
var firstGroup = svg.querySelector("g");
expect(firstGroup.getAttribute("transform")).toEqual("translate(0,10)");
var secondGroup = firstGroup.childNodes[1];
expect(secondGroup.getAttribute("transform")).toEqual("translate(40,40)");
var thirdGroup = firstGroup.childNodes[2];
expect(thirdGroup.getAttribute("transform")).toEqual("translate(0,10)");
});
});
describe("it will generate ids", function() {
it("that start with a letter", function() {
var ctx = new C2S();
ctx.createRadialGradient(6E1, 6E1, 0.0, 6E1, 6E1, 5E1);
var svg = ctx.getSvg();
var id = svg.children[0].children[0].id;
var test = /^[A-Za-z]/.test(id);
expect(test).toEqual(true);
});
});
describe("will split up rgba", function() {
//while browsers support rgba values for fill/stroke, this is not accepted in visio/illustrator
it("to fill and fill-opacity", function() {
var ctx = new C2S();
ctx.fillStyle="rgba(20,40,50,0.5)";
ctx.fillRect(100,100,100,100);
var svg = ctx.getSvg();
expect(svg.querySelector("rect").getAttribute("fill")).toBe("rgb(20,40,50)");
expect(svg.querySelector("rect").getAttribute("fill-opacity")).toBe("0.5");
});
it("to stroke and stroke-opacity", function() {
var ctx = new C2S();
ctx.strokeStyle="rgba(10,20,30,0.4)";
ctx.strokeRect(100,100,100,100);
var svg = ctx.getSvg();
expect(svg.querySelector("rect").getAttribute("stroke")).toBe("rgb(10,20,30)");
expect(svg.querySelector("rect").getAttribute("stroke-opacity")).toBe("0.4");
});
});
describe("supports path commands", function() {
it("and moveTo may be called without beginPath, but is not recommended", function() {
var ctx = new C2S();
ctx.moveTo(0,0);
ctx.lineTo(100,100);
ctx.stroke();
});
});
describe("supports text align", function() {
it("not specifying a value defaults to 'start'", function() {
var ctx = new C2S();
ctx.font = "normal 36px Times";
ctx.fillStyle = "#000000";
ctx.fillText("A Text Example", 0, 50);
var svg = ctx.getSvg();
expect(svg.querySelector("text").getAttribute("text-anchor")).toBe("start");
});
it("assuming ltr, left maps to 'start'", function() {
var ctx = new C2S();
ctx.textAlign = "left";
ctx.font = "normal 36px Times";
ctx.fillStyle = "#000000";
ctx.fillText("A Text Example", 0, 50);
var svg = ctx.getSvg();
expect(svg.querySelector("text").getAttribute("text-anchor")).toBe("start");
});
it("assuming ltr, right maps to 'end'", function() {
var ctx = new C2S();
ctx.textAlign = "right";
ctx.font = "normal 36px Times";
ctx.fillStyle = "#000000";
ctx.fillText("A Text Example", 0, 50);
var svg = ctx.getSvg();
expect(svg.querySelector("text").getAttribute("text-anchor")).toBe("end");
});
it("center maps to 'middle'", function() {
var ctx = new C2S();
ctx.textAlign = "center";
ctx.font = "normal 36px Times";
ctx.fillStyle = "#000000";
ctx.fillText("A Text Example", 0, 50);
var svg = ctx.getSvg();
expect(svg.querySelector("text").getAttribute("text-anchor")).toBe("middle");
});
it("stores the proper values on save and restore", function() {
var ctx = new C2S();
ctx.textAlign = "center";
expect(ctx.textAlign).toBe("center");
ctx.save();
expect(ctx.textAlign).toBe("center");
ctx.textAlign = "right";
expect(ctx.textAlign).toBe("right");
ctx.restore();
expect(ctx.textAlign).toBe("center");
});
});
describe("supports text baseline", function() {
it("not specifying a value defaults to alphabetic", function() {
var ctx = new C2S();
ctx.font = "normal 36px Times";
ctx.fillStyle = "#000000";
ctx.fillText("A Text Example", 0, 50);
var svg = ctx.getSvg();
expect(svg.querySelector("text").getAttribute("dominant-baseline")).toBe("alphabetic");
});
it("not specifying a valid value defaults to alphabetic", function() {
var ctx = new C2S();
ctx.font = "normal 36px Times";
ctx.fillStyle = "#000000";
ctx.textBaseline = "werwerwer";
ctx.fillText("A Text Example", 0, 50);
var svg = ctx.getSvg();
expect(svg.querySelector("text").getAttribute("dominant-baseline")).toBe("alphabetic");
});
it("hanging maps to hanging ", function() {
var ctx = new C2S();
ctx.font = "normal 36px Times";
ctx.fillStyle = "#000000";
ctx.textBaseline = "hanging";
ctx.fillText("A Text Example", 0, 50);
var svg = ctx.getSvg();
expect(svg.querySelector("text").getAttribute("dominant-baseline")).toBe("hanging");
});
it("top maps to text-before-edge ", function() {
var ctx = new C2S();
ctx.font = "normal 36px Times";
ctx.fillStyle = "#000000";
ctx.textBaseline = "top";
ctx.fillText("A Text Example", 0, 50);
var svg = ctx.getSvg();
expect(svg.querySelector("text").getAttribute("dominant-baseline")).toBe("text-before-edge");
});
it("bottom maps to text-after-edge ", function() {
var ctx = new C2S();
ctx.font = "normal 36px Times";
ctx.fillStyle = "#000000";
ctx.textBaseline = "bottom";
ctx.fillText("A Text Example", 0, 50);
var svg = ctx.getSvg();
expect(svg.querySelector("text").getAttribute("dominant-baseline")).toBe("text-after-edge");
});
it("middle maps to central ", function() {
var ctx = new C2S();
ctx.font = "normal 36px Times";
ctx.fillStyle = "#000000";
ctx.textBaseline = "middle";
ctx.fillText("A Text Example", 0, 50);
var svg = ctx.getSvg();
expect(svg.querySelector("text").getAttribute("dominant-baseline")).toBe("central");
});
});
});

32
karma.conf.js Normal file
View File

@ -0,0 +1,32 @@
module.exports = function(config) {
config.set({
basePath: '',
frameworks: ['mocha', 'chai'],
plugins: [
'karma-mocha',
'karma-chai',
'karma-mocha-reporter',
'karma-chrome-launcher',
'karma-firefox-launcher'
],
client: {
},
files: [
'node_modules/resemblejs/resemble.js',
'canvas2svg.js',
'test/globals.js',
'test/example/*.js',
'test/unit.spec.js',
'test/example.spec.js'
],
preprocessors: {
},
reporters: ['mocha'],
port: 9876,
colors: true,
logLevel: config.LOG_DISABLE,
autoWatch: false,
browsers: ['Firefox', 'Chrome'],
singleRun: true
});
};

34
package.json Normal file
View File

@ -0,0 +1,34 @@
{
"name": "canvas2svg",
"version": "1.0.14",
"description": "canvas2svg",
"main": "canvas2svg.js",
"homepage": "http://gliffy.github.io/canvas2svg/",
"directories": {
"test": "test"
},
"scripts": {
"test": "./node_modules/.bin/karma start --browsers Firefox --single-run"
},
"keywords": [
"canvas",
"svg",
"canvas2svg"
],
"author": "Kerry Liu",
"license": "MIT",
"dependencies": {},
"devDependencies": {
"chai": "^2.1.1",
"cheerio": "^0.19.0",
"gulp": "^3.9.0",
"karma": "^0.12.36",
"karma-chai": "^0.1.0",
"karma-chrome-launcher": "^0.1.12",
"karma-firefox-launcher": "^0.1.6",
"karma-mocha": "^0.1.10",
"karma-mocha-reporter": "^1.0.2",
"mocha": "^2.2.5",
"resemblejs": "^1.2.1"
}
}

427
test/css/normalize.css vendored Normal file
View File

@ -0,0 +1,427 @@
/*! normalize.css v3.0.2 | MIT License | git.io/normalize */
/**
* 1. Set default font family to sans-serif.
* 2. Prevent iOS text size adjust after orientation change, without disabling
* user zoom.
*/
html {
font-family: sans-serif; /* 1 */
-ms-text-size-adjust: 100%; /* 2 */
-webkit-text-size-adjust: 100%; /* 2 */
}
/**
* Remove default margin.
*/
body {
margin: 0;
}
/* HTML5 display definitions
========================================================================== */
/**
* Correct `block` display not defined for any HTML5 element in IE 8/9.
* Correct `block` display not defined for `details` or `summary` in IE 10/11
* and Firefox.
* Correct `block` display not defined for `main` in IE 11.
*/
article,
aside,
details,
figcaption,
figure,
footer,
header,
hgroup,
main,
menu,
nav,
section,
summary {
display: block;
}
/**
* 1. Correct `inline-block` display not defined in IE 8/9.
* 2. Normalize vertical alignment of `progress` in Chrome, Firefox, and Opera.
*/
audio,
canvas,
progress,
video {
display: inline-block; /* 1 */
vertical-align: baseline; /* 2 */
}
/**
* Prevent modern browsers from displaying `audio` without controls.
* Remove excess height in iOS 5 devices.
*/
audio:not([controls]) {
display: none;
height: 0;
}
/**
* Address `[hidden]` styling not present in IE 8/9/10.
* Hide the `template` element in IE 8/9/11, Safari, and Firefox < 22.
*/
[hidden],
template {
display: none;
}
/* Links
========================================================================== */
/**
* Remove the gray background color from active links in IE 10.
*/
a {
background-color: transparent;
}
/**
* Improve readability when focused and also mouse hovered in all browsers.
*/
a:active,
a:hover {
outline: 0;
}
/* Text-level semantics
========================================================================== */
/**
* Address styling not present in IE 8/9/10/11, Safari, and Chrome.
*/
abbr[title] {
border-bottom: 1px dotted;
}
/**
* Address style set to `bolder` in Firefox 4+, Safari, and Chrome.
*/
b,
strong {
font-weight: bold;
}
/**
* Address styling not present in Safari and Chrome.
*/
dfn {
font-style: italic;
}
/**
* Address variable `h1` font-size and margin within `section` and `article`
* contexts in Firefox 4+, Safari, and Chrome.
*/
h1 {
font-size: 2em;
margin: 0.67em 0;
}
/**
* Address styling not present in IE 8/9.
*/
mark {
background: #ff0;
color: #000;
}
/**
* Address inconsistent and variable font size in all browsers.
*/
small {
font-size: 80%;
}
/**
* Prevent `sub` and `sup` affecting `line-height` in all browsers.
*/
sub,
sup {
font-size: 75%;
line-height: 0;
position: relative;
vertical-align: baseline;
}
sup {
top: -0.5em;
}
sub {
bottom: -0.25em;
}
/* Embedded content
========================================================================== */
/**
* Remove border when inside `a` element in IE 8/9/10.
*/
img {
border: 0;
}
/**
* Correct overflow not hidden in IE 9/10/11.
*/
svg:not(:root) {
overflow: hidden;
}
/* Grouping content
========================================================================== */
/**
* Address margin not present in IE 8/9 and Safari.
*/
figure {
margin: 1em 40px;
}
/**
* Address differences between Firefox and other browsers.
*/
hr {
-moz-box-sizing: content-box;
box-sizing: content-box;
height: 0;
}
/**
* Contain overflow in all browsers.
*/
pre {
overflow: auto;
}
/**
* Address odd `em`-unit font size rendering in all browsers.
*/
code,
kbd,
pre,
samp {
font-family: monospace, monospace;
font-size: 1em;
}
/* Forms
========================================================================== */
/**
* Known limitation: by default, Chrome and Safari on OS X allow very limited
* styling of `select`, unless a `border` property is set.
*/
/**
* 1. Correct color not being inherited.
* Known issue: affects color of disabled elements.
* 2. Correct font properties not being inherited.
* 3. Address margins set differently in Firefox 4+, Safari, and Chrome.
*/
button,
input,
optgroup,
select,
textarea {
color: inherit; /* 1 */
font: inherit; /* 2 */
margin: 0; /* 3 */
}
/**
* Address `overflow` set to `hidden` in IE 8/9/10/11.
*/
button {
overflow: visible;
}
/**
* Address inconsistent `text-transform` inheritance for `button` and `select`.
* All other form control elements do not inherit `text-transform` values.
* Correct `button` style inheritance in Firefox, IE 8/9/10/11, and Opera.
* Correct `select` style inheritance in Firefox.
*/
button,
select {
text-transform: none;
}
/**
* 1. Avoid the WebKit bug in Android 4.0.* where (2) destroys native `audio`
* and `video` controls.
* 2. Correct inability to style clickable `input` types in iOS.
* 3. Improve usability and consistency of cursor style between image-type
* `input` and others.
*/
button,
html input[type="button"], /* 1 */
input[type="reset"],
input[type="submit"] {
-webkit-appearance: button; /* 2 */
cursor: pointer; /* 3 */
}
/**
* Re-set default cursor for disabled elements.
*/
button[disabled],
html input[disabled] {
cursor: default;
}
/**
* Remove inner padding and border in Firefox 4+.
*/
button::-moz-focus-inner,
input::-moz-focus-inner {
border: 0;
padding: 0;
}
/**
* Address Firefox 4+ setting `line-height` on `input` using `!important` in
* the UA stylesheet.
*/
input {
line-height: normal;
}
/**
* It's recommended that you don't attempt to style these elements.
* Firefox's implementation doesn't respect box-sizing, padding, or width.
*
* 1. Address box sizing set to `content-box` in IE 8/9/10.
* 2. Remove excess padding in IE 8/9/10.
*/
input[type="checkbox"],
input[type="radio"] {
box-sizing: border-box; /* 1 */
padding: 0; /* 2 */
}
/**
* Fix the cursor style for Chrome's increment/decrement buttons. For certain
* `font-size` values of the `input`, it causes the cursor style of the
* decrement button to change from `default` to `text`.
*/
input[type="number"]::-webkit-inner-spin-button,
input[type="number"]::-webkit-outer-spin-button {
height: auto;
}
/**
* 1. Address `appearance` set to `searchfield` in Safari and Chrome.
* 2. Address `box-sizing` set to `border-box` in Safari and Chrome
* (include `-moz` to future-proof).
*/
input[type="search"] {
-webkit-appearance: textfield; /* 1 */
-moz-box-sizing: content-box;
-webkit-box-sizing: content-box; /* 2 */
box-sizing: content-box;
}
/**
* Remove inner padding and search cancel button in Safari and Chrome on OS X.
* Safari (but not Chrome) clips the cancel button when the search input has
* padding (and `textfield` appearance).
*/
input[type="search"]::-webkit-search-cancel-button,
input[type="search"]::-webkit-search-decoration {
-webkit-appearance: none;
}
/**
* Define consistent border, margin, and padding.
*/
fieldset {
border: 1px solid #c0c0c0;
margin: 0 2px;
padding: 0.35em 0.625em 0.75em;
}
/**
* 1. Correct `color` not being inherited in IE 8/9/10/11.
* 2. Remove padding so people aren't caught out if they zero out fieldsets.
*/
legend {
border: 0; /* 1 */
padding: 0; /* 2 */
}
/**
* Remove default vertical scrollbar in IE 8/9/10/11.
*/
textarea {
overflow: auto;
}
/**
* Don't inherit the `font-weight` (applied by a rule above).
* NOTE: the default cannot safely be changed in Chrome and Safari on OS X.
*/
optgroup {
font-weight: bold;
}
/* Tables
========================================================================== */
/**
* Remove most spacing between table cells.
*/
table {
border-collapse: collapse;
border-spacing: 0;
}
td,
th {
padding: 0;
}

15
test/css/playground.css Normal file
View File

@ -0,0 +1,15 @@
#canvas,
#svg {
border: 1px solid #CCC;
}
#svg {
width: 460px;
height: 460px;
overflow: hidden;
}
.container,
.try {
margin-top: 20px;
}

418
test/css/skeleton.css vendored Normal file
View File

@ -0,0 +1,418 @@
/*
* Skeleton V2.0.4
* Copyright 2014, Dave Gamache
* www.getskeleton.com
* Free to use under the MIT license.
* http://www.opensource.org/licenses/mit-license.php
* 12/29/2014
*/
/* Table of contents
- Grid
- Base Styles
- Typography
- Links
- Buttons
- Forms
- Lists
- Code
- Tables
- Spacing
- Utilities
- Clearing
- Media Queries
*/
/* Grid
*/
.container {
position: relative;
width: 100%;
max-width: 960px;
margin: 0 auto;
padding: 0 20px;
box-sizing: border-box; }
.column,
.columns {
width: 100%;
float: left;
box-sizing: border-box; }
/* For devices larger than 400px */
@media (min-width: 400px) {
.container {
width: 85%;
padding: 0; }
}
/* For devices larger than 550px */
@media (min-width: 550px) {
.container {
width: 80%; }
.column,
.columns {
margin-left: 4%; }
.column:first-child,
.columns:first-child {
margin-left: 0; }
.one.column,
.one.columns { width: 4.66666666667%; }
.two.columns { width: 13.3333333333%; }
.three.columns { width: 22%; }
.four.columns { width: 30.6666666667%; }
.five.columns { width: 39.3333333333%; }
.six.columns { width: 48%; }
.seven.columns { width: 56.6666666667%; }
.eight.columns { width: 65.3333333333%; }
.nine.columns { width: 74.0%; }
.ten.columns { width: 82.6666666667%; }
.eleven.columns { width: 91.3333333333%; }
.twelve.columns { width: 100%; margin-left: 0; }
.one-third.column { width: 30.6666666667%; }
.two-thirds.column { width: 65.3333333333%; }
.one-half.column { width: 48%; }
/* Offsets */
.offset-by-one.column,
.offset-by-one.columns { margin-left: 8.66666666667%; }
.offset-by-two.column,
.offset-by-two.columns { margin-left: 17.3333333333%; }
.offset-by-three.column,
.offset-by-three.columns { margin-left: 26%; }
.offset-by-four.column,
.offset-by-four.columns { margin-left: 34.6666666667%; }
.offset-by-five.column,
.offset-by-five.columns { margin-left: 43.3333333333%; }
.offset-by-six.column,
.offset-by-six.columns { margin-left: 52%; }
.offset-by-seven.column,
.offset-by-seven.columns { margin-left: 60.6666666667%; }
.offset-by-eight.column,
.offset-by-eight.columns { margin-left: 69.3333333333%; }
.offset-by-nine.column,
.offset-by-nine.columns { margin-left: 78.0%; }
.offset-by-ten.column,
.offset-by-ten.columns { margin-left: 86.6666666667%; }
.offset-by-eleven.column,
.offset-by-eleven.columns { margin-left: 95.3333333333%; }
.offset-by-one-third.column,
.offset-by-one-third.columns { margin-left: 34.6666666667%; }
.offset-by-two-thirds.column,
.offset-by-two-thirds.columns { margin-left: 69.3333333333%; }
.offset-by-one-half.column,
.offset-by-one-half.columns { margin-left: 52%; }
}
/* Base Styles
*/
/* NOTE
html is set to 62.5% so that all the REM measurements throughout Skeleton
are based on 10px sizing. So basically 1.5rem = 15px :) */
html {
font-size: 62.5%; }
body {
font-size: 1.5em; /* currently ems cause chrome bug misinterpreting rems on body element */
line-height: 1.6;
font-weight: 400;
font-family: "Raleway", "HelveticaNeue", "Helvetica Neue", Helvetica, Arial, sans-serif;
color: #222; }
/* Typography
*/
h1, h2, h3, h4, h5, h6 {
margin-top: 0;
margin-bottom: 2rem;
font-weight: 300; }
h1 { font-size: 4.0rem; line-height: 1.2; letter-spacing: -.1rem;}
h2 { font-size: 3.6rem; line-height: 1.25; letter-spacing: -.1rem; }
h3 { font-size: 3.0rem; line-height: 1.3; letter-spacing: -.1rem; }
h4 { font-size: 2.4rem; line-height: 1.35; letter-spacing: -.08rem; }
h5 { font-size: 1.8rem; line-height: 1.5; letter-spacing: -.05rem; }
h6 { font-size: 1.5rem; line-height: 1.6; letter-spacing: 0; }
/* Larger than phablet */
@media (min-width: 550px) {
h1 { font-size: 5.0rem; }
h2 { font-size: 4.2rem; }
h3 { font-size: 3.6rem; }
h4 { font-size: 3.0rem; }
h5 { font-size: 2.4rem; }
h6 { font-size: 1.5rem; }
}
p {
margin-top: 0; }
/* Links
*/
a {
color: #1EAEDB; }
a:hover {
color: #0FA0CE; }
/* Buttons
*/
.button,
button,
input[type="submit"],
input[type="reset"],
input[type="button"] {
display: inline-block;
height: 38px;
padding: 0 30px;
color: #555;
text-align: center;
font-size: 11px;
font-weight: 600;
line-height: 38px;
letter-spacing: .1rem;
text-transform: uppercase;
text-decoration: none;
white-space: nowrap;
background-color: transparent;
border-radius: 4px;
border: 1px solid #bbb;
cursor: pointer;
box-sizing: border-box; }
.button:hover,
button:hover,
input[type="submit"]:hover,
input[type="reset"]:hover,
input[type="button"]:hover,
.button:focus,
button:focus,
input[type="submit"]:focus,
input[type="reset"]:focus,
input[type="button"]:focus {
color: #333;
border-color: #888;
outline: 0; }
.button.button-primary,
button.button-primary,
input[type="submit"].button-primary,
input[type="reset"].button-primary,
input[type="button"].button-primary {
color: #FFF;
background-color: #33C3F0;
border-color: #33C3F0; }
.button.button-primary:hover,
button.button-primary:hover,
input[type="submit"].button-primary:hover,
input[type="reset"].button-primary:hover,
input[type="button"].button-primary:hover,
.button.button-primary:focus,
button.button-primary:focus,
input[type="submit"].button-primary:focus,
input[type="reset"].button-primary:focus,
input[type="button"].button-primary:focus {
color: #FFF;
background-color: #1EAEDB;
border-color: #1EAEDB; }
/* Forms
*/
input[type="email"],
input[type="number"],
input[type="search"],
input[type="text"],
input[type="tel"],
input[type="url"],
input[type="password"],
textarea,
select {
height: 38px;
padding: 6px 10px; /* The 6px vertically centers text on FF, ignored by Webkit */
background-color: #fff;
border: 1px solid #D1D1D1;
border-radius: 4px;
box-shadow: none;
box-sizing: border-box; }
/* Removes awkward default styles on some inputs for iOS */
input[type="email"],
input[type="number"],
input[type="search"],
input[type="text"],
input[type="tel"],
input[type="url"],
input[type="password"],
textarea {
-webkit-appearance: none;
-moz-appearance: none;
appearance: none; }
textarea {
min-height: 65px;
padding-top: 6px;
padding-bottom: 6px; }
input[type="email"]:focus,
input[type="number"]:focus,
input[type="search"]:focus,
input[type="text"]:focus,
input[type="tel"]:focus,
input[type="url"]:focus,
input[type="password"]:focus,
textarea:focus,
select:focus {
border: 1px solid #33C3F0;
outline: 0; }
label,
legend {
display: block;
margin-bottom: .5rem;
font-weight: 600; }
fieldset {
padding: 0;
border-width: 0; }
input[type="checkbox"],
input[type="radio"] {
display: inline; }
label > .label-body {
display: inline-block;
margin-left: .5rem;
font-weight: normal; }
/* Lists
*/
ul {
list-style: circle inside; }
ol {
list-style: decimal inside; }
ol, ul {
padding-left: 0;
margin-top: 0; }
ul ul,
ul ol,
ol ol,
ol ul {
margin: 1.5rem 0 1.5rem 3rem;
font-size: 90%; }
li {
margin-bottom: 1rem; }
/* Code
*/
code {
padding: .2rem .5rem;
margin: 0 .2rem;
font-size: 90%;
white-space: nowrap;
background: #F1F1F1;
border: 1px solid #E1E1E1;
border-radius: 4px; }
pre > code {
display: block;
padding: 1rem 1.5rem;
white-space: pre; }
/* Tables
*/
th,
td {
padding: 12px 15px;
text-align: left;
border-bottom: 1px solid #E1E1E1; }
th:first-child,
td:first-child {
padding-left: 0; }
th:last-child,
td:last-child {
padding-right: 0; }
/* Spacing
*/
button,
.button {
margin-bottom: 1rem; }
input,
textarea,
select,
fieldset {
margin-bottom: 1.5rem; }
pre,
blockquote,
dl,
figure,
table,
p,
ul,
ol,
form {
margin-bottom: 2.5rem; }
/* Utilities
*/
.u-full-width {
width: 100%;
box-sizing: border-box; }
.u-max-full-width {
max-width: 100%;
box-sizing: border-box; }
.u-pull-right {
float: right; }
.u-pull-left {
float: left; }
/* Misc
*/
hr {
margin-top: 3rem;
margin-bottom: 3.5rem;
border-width: 0;
border-top: 1px solid #E1E1E1; }
/* Clearing
*/
/* Self Clearing Goodness */
.container:after,
.row:after,
.u-cf {
content: "";
display: table;
clear: both; }
/* Media Queries
*/
/*
Note: The best way to structure the use of media queries is to create the queries
near the relevant code. For example, if you wanted to change the styles for buttons
on small devices, paste the mobile query code up in the buttons section and style it
there.
*/
/* Larger than mobile */
@media (min-width: 400px) {}
/* Larger than phablet (also point when grid becomes active) */
@media (min-width: 550px) {}
/* Larger than tablet */
@media (min-width: 750px) {}
/* Larger than desktop */
@media (min-width: 1000px) {}
/* Larger than Desktop HD */
@media (min-width: 1200px) {}

85
test/example.spec.js Normal file
View File

@ -0,0 +1,85 @@
describe('canvas2svg exports', function() {
var examples = Object.keys(C2S_EXAMPLES);
var C2S_WIDTH = 600;
var C2S_HEIGHT = 600;
var imgdata, svgimgdata, diffdata;
function drawExample (example) {
var canvas = document.createElement('canvas');
canvas.setAttribute('width', C2S_WIDTH);
canvas.setAttribute('height', C2S_HEIGHT);
document.body.appendChild(canvas);
var ctx = canvas.getContext("2d");
ctx.clearRect(0, 0, C2S_WIDTH, C2S_HEIGHT);
var c2s = new C2S(C2S_WIDTH, C2S_HEIGHT);
example(ctx);
example(c2s);
imgdata = canvas.toDataURL();
svgimgdata = "data:image/svg+xml;charset=utf-8,"+c2s.getSerializedSvg(true);
}
function cleanUp () {
var canvases = document.querySelectorAll('canvas');
var i;
//Node Array doesn't implement array methods :/
for(i=0; i<canvases.length; i++) {
canvases[i].parentElement.removeChild(canvases[i]);
}
}
examples.forEach(function(example) {
describe(example, function() {
var drawFunction;
beforeEach(function() {
drawFunction = C2S_EXAMPLES[example];
});
it('to svg (left is canvas right is svg)', function () {
drawExample(drawFunction);
});
//test is async, pass in done
it('resembles each other', function() {
// see: https://github.com/Huddle/Resemble.js
var diff = resemble(imgdata).compareTo(svgimgdata).ignoreAntialiasing().onComplete(function(data){
diffdata = data;
expect(data.misMatchPercentage).to.be.below(0.30);
});
});
after(function() {
cleanUp();
var lis = document.querySelectorAll('li');
//on server side, don't inject images
if(lis.length > 0) {
//append svg + canvas images
var li = lis[lis.length - 2];
var image = document.createElement('img');
image.setAttribute('src', imgdata);
image.setAttribute('style', 'display:inline-block;');
var svgimage = document.createElement('img');
svgimage.setAttribute('src', svgimgdata);
svgimage.setAttribute('style', 'display:inline-block;');
li.appendChild(image);
li.appendChild(svgimage);
// append diff data
li = lis[lis.length-1];
var diffimage = document.createElement('img');
diffimage.setAttribute('src', diffdata.getImageDataUrl());
diffimage.setAttribute('style', 'display:inline-block;');
li.appendChild(diffimage);
}
});
});
});
});

24
test/example/arc.js Normal file
View File

@ -0,0 +1,24 @@
window.C2S_EXAMPLES['arc'] = function(ctx) {
// Draw shapes
for (i = 0; i < 4; i++) {
for (j = 0; j < 3; j++) {
ctx.beginPath();
var x = 25 + j * 50; // x coordinate
var y = 25 + i * 50; // y coordinate
var radius = 20; // Arc radius
var startAngle = 0; // Starting point on circle
var endAngle = Math.PI + (Math.PI * j) / 2; // End point on circle
var clockwise = i % 2 == 0 ? false : true; // clockwise or anticlockwise
ctx.arc(x, y, radius, startAngle, endAngle, clockwise);
if (i > 1) {
ctx.fill();
} else {
ctx.stroke();
}
}
}
};

16
test/example/arcTo.js Normal file
View File

@ -0,0 +1,16 @@
window.C2S_EXAMPLES['arcTo'] = function (ctx) {
ctx.beginPath();
ctx.moveTo(150, 20);
ctx.arcTo(150, 100, 50, 20, 30);
ctx.stroke();
ctx.fillStyle = 'blue';
// base point
ctx.fillRect(150, 20, 10, 10);
ctx.fillStyle = 'red';
// control point one
ctx.fillRect(150, 100, 10, 10);
// control point two
ctx.fillRect(50, 20, 10, 10);
};

7
test/example/arcTo2.js Normal file
View File

@ -0,0 +1,7 @@
window.C2S_EXAMPLES['arcTo2'] = function(ctx) {
ctx.beginPath();
ctx.moveTo(100, 225); // P0
ctx.arcTo(300, 25, 500, 225, 75); // P1, P2 and the radius
ctx.lineTo(500, 225); // P2
ctx.stroke();
};

View File

@ -0,0 +1,9 @@
window.C2S_EXAMPLES['fillstyle'] = function(ctx) {
for (var i = 0; i < 6; i++) {
for (var j = 0; j < 6; j++) {
ctx.fillStyle = 'rgb(' + Math.floor(255 - 42.5 * i) + ',' +
Math.floor(255 - 42.5 * j) + ',0)';
ctx.fillRect(j * 25, i * 25, 25, 25);
}
}
};

View File

@ -0,0 +1,23 @@
window.C2S_EXAMPLES['globalalpha'] = function(ctx) {
ctx.fillStyle = '#FD0';
ctx.fillRect(0,0,75,75);
ctx.fillStyle = '#6C0';
ctx.fillRect(75,0,75,75);
ctx.fillStyle = '#09F';
ctx.fillRect(0,75,75,75);
ctx.fillStyle = '#F30';
ctx.fillRect(75,75,75,75);
ctx.fillStyle = '#FFF';
// set transparency value
ctx.globalAlpha = 0.2;
// Draw semi transparent circles
for (i=0;i<7;i++){
ctx.beginPath();
ctx.arc(75,75,10+10*i,0,Math.PI*2,true);
ctx.fill();
}
ctx.globalAlpha = 1.0;
};

49
test/example/gradient.js Normal file
View File

@ -0,0 +1,49 @@
window.C2S_EXAMPLES['gradient'] = function(ctx) {
ctx.save();
ctx.strokeStyle='rgba(0,0,0,0)';
ctx.lineCap='butt';
ctx.lineJoin='miter';
ctx.miterLimit=10.0;
ctx.font='10px sans-serif';
ctx.save();
var radialGradient_1389130830351 = ctx.createRadialGradient(6E1,6E1,0.0,6E1,6E1,5E1);
radialGradient_1389130830351.addColorStop(0E0,'red');
radialGradient_1389130830351.addColorStop(1E0,'blue');
ctx.fillStyle=radialGradient_1389130830351;
ctx.font='10px sans-serif';
ctx.beginPath();
ctx.moveTo(2.5E1,1E1);
ctx.lineTo(9.5E1,1E1);
ctx.quadraticCurveTo(1.1E2,1E1,1.1E2,2.5E1);
ctx.lineTo(1.1E2,9.5E1);
ctx.quadraticCurveTo(1.1E2,1.1E2,9.5E1,1.1E2);
ctx.lineTo(2.5E1,1.1E2);
ctx.quadraticCurveTo(1E1,1.1E2,1E1,9.5E1);
ctx.lineTo(1E1,2.5E1);
ctx.quadraticCurveTo(1E1,1E1,2.5E1,1E1);
ctx.closePath();
ctx.fill();
ctx.stroke();
ctx.restore();
ctx.save();
var radialGradient_1389130830351 = ctx.createRadialGradient(3.5E1,1.45E2,0.0,3.5E1,1.45E2,2.5E1);
radialGradient_1389130830351.addColorStop(0E0,'red');
radialGradient_1389130830351.addColorStop(1E0,'blue');
ctx.fillStyle=radialGradient_1389130830351;
ctx.font='10px sans-serif';
ctx.beginPath();
ctx.moveTo(2.5E1,1.2E2);
ctx.lineTo(9.5E1,1.2E2);
ctx.quadraticCurveTo(1.1E2,1.2E2,1.1E2,1.35E2);
ctx.lineTo(1.1E2,2.05E2);
ctx.quadraticCurveTo(1.1E2,2.2E2,9.5E1,2.2E2);
ctx.lineTo(2.5E1,2.2E2);
ctx.quadraticCurveTo(1E1,2.2E2,1E1,2.05E2);
ctx.lineTo(1E1,1.35E2);
ctx.quadraticCurveTo(1E1,1.2E2,2.5E1,1.2E2);
ctx.closePath();
ctx.fill();
ctx.stroke();
ctx.restore();
ctx.restore();
};

23
test/example/linecap.js Normal file
View File

@ -0,0 +1,23 @@
window.C2S_EXAMPLES['linecap'] = function(ctx) {
var lineCap = ['butt','round','square'];
// Draw guides
ctx.strokeStyle = '#09f';
ctx.beginPath();
ctx.moveTo(10,10);
ctx.lineTo(140,10);
ctx.moveTo(10,140);
ctx.lineTo(140,140);
ctx.stroke();
// Draw lines
ctx.strokeStyle = 'black';
for (var i=0;i<lineCap.length;i++){
ctx.lineWidth = 15;
ctx.lineCap = lineCap[i];
ctx.beginPath();
ctx.moveTo(25+i*50,10);
ctx.lineTo(25+i*50,140);
ctx.stroke();
}
}

View File

@ -0,0 +1,9 @@
window.C2S_EXAMPLES['linewidth'] = function(ctx) {
for (var i = 0; i < 10; i++){
ctx.lineWidth = 1+i;
ctx.beginPath();
ctx.moveTo(5+i*14,5);
ctx.lineTo(5+i*14,140);
ctx.stroke();
}
};

19
test/example/rgba.js Normal file
View File

@ -0,0 +1,19 @@
window.C2S_EXAMPLES['rgba'] = function(ctx) {
// Draw background
ctx.fillStyle = 'rgb(255,221,0)';
ctx.fillRect(0,0,150,37.5);
ctx.fillStyle = 'rgb(102,204,0)';
ctx.fillRect(0,37.5,150,37.5);
ctx.fillStyle = 'rgb(0,153,255)';
ctx.fillRect(0,75,150,37.5);
ctx.fillStyle = 'rgb(255,51,0)';
ctx.fillRect(0,112.5,150,37.5);
// Draw semi transparent rectangles
for (var i=0;i<10;i++){
ctx.fillStyle = 'rgba(255,255,255,'+(i+1)/10+')';
for (var j=0;j<4;j++){
ctx.fillRect(5+i*14,5+j*37.5,14,27.5);
}
}
}

View File

@ -0,0 +1,18 @@
window.C2S_EXAMPLES['saveandrestore'] = function (ctx) {
ctx.fillRect(0, 0, 150, 150); // Draw a rectangle with default settings
ctx.save(); // Save the default state
ctx.fillStyle = '#09F'; // Make changes to the settings
ctx.fillRect(15, 15, 120, 120); // Draw a rectangle with new settings
ctx.save(); // Save the current state
ctx.fillStyle = '#FFF'; // Make changes to the settings
ctx.globalAlpha = 0.5;
ctx.fillRect(30, 30, 90, 90); // Draw a rectangle with new settings
ctx.restore(); // Restore previous state
ctx.fillRect(45, 45, 60, 60); // Draw a rectangle with restored settings
ctx.restore(); // Restore original state
ctx.fillRect(60, 60, 30, 30); // Draw a rectangle with restored settings
};

8
test/example/text.js Normal file
View File

@ -0,0 +1,8 @@
window.C2S_EXAMPLES['text'] = function(ctx) {
ctx.font = "normal 36px Times";
ctx.fillStyle = "#000000";
ctx.fillText("A Text Example", 50, 50);
ctx.font = "normal 36px Arial";
ctx.strokeStyle = "#000000";
ctx.strokeText("A Text Example", 50, 90);
};

5918
test/example/tiger.js Normal file

File diff suppressed because it is too large Load Diff

1
test/globals.js Normal file
View File

@ -0,0 +1 @@
window.C2S_EXAMPLES = {};

105
test/playground.html Normal file
View File

@ -0,0 +1,105 @@
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Canvas2Svg Playground</title>
<link rel="stylesheet" href="css/normalize.css">
<link rel="stylesheet" href="css/skeleton.css">
<link rel="stylesheet" href="css/playground.css">
</head>
<body>
<div class="container">
<form>
<div class="row">
<div class="twelve columns">
<h5>Select an example</h5>
</div>
</div>
</form>
<form>
<div class="row">
<div class="twelve columns">
<!-- select content is generated by the command `gulp update_examples` -->
<select id="select" class="u-full-width"><option value="arc">arc</option><option value="arcTo">arcTo</option><option value="arcTo2">arcTo2</option><option value="fillstyle">fillstyle</option><option value="globalalpha">globalalpha</option><option value="gradient">gradient</option><option value="linecap">linecap</option><option value="linewidth">linewidth</option><option value="rgba">rgba</option><option value="saveandrestore">saveandrestore</option><option value="text">text</option><option value="tiger">tiger</option></select>
</div>
</div>
</form>
<div class="row">
<div class="six columns">
<h5>Canvas</h5>
</div>
<div class="six columns">
<h5>SVG</h5>
</div>
</div>
<div class="row">
<div class="six columns">
<canvas id="canvas" width="460" height="460"></canvas>
</div>
<div class="six columns" id="svg">
</div>
</div>
<br>
<div class="row try">
<div class="twelve columns">
<h5>Or try your own!</h5>
</div>
</div>
<div class="row">
<div class="twelve columns">
<textarea id="textarea" class="u-full-width" placeholder="//ctx.fillRect(0,0,100,100);"></textarea>
</div>
</div>
<div class="row">
<div class="twelve columns">
<a href="#" class="button button-primary u-pull-right" id="render">Render</a>
</div>
</div>
</div>
<!-- jQuery is only used for convenience on this test page, it's not a dependency for the library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type="text/javascript" src="../canvas2svg.js"></script>
<script type="text/javascript">
window.C2S_EXAMPLES = {};
</script>
<!-- examples content is generated by the command `gulp update_examples` -->
<div id="examples"><script type="text/javascript" src="example/arc.js"></script><script type="text/javascript" src="example/arcTo.js"></script><script type="text/javascript" src="example/arcTo2.js"></script><script type="text/javascript" src="example/fillstyle.js"></script><script type="text/javascript" src="example/globalalpha.js"></script><script type="text/javascript" src="example/gradient.js"></script><script type="text/javascript" src="example/linecap.js"></script><script type="text/javascript" src="example/linewidth.js"></script><script type="text/javascript" src="example/rgba.js"></script><script type="text/javascript" src="example/saveandrestore.js"></script><script type="text/javascript" src="example/text.js"></script><script type="text/javascript" src="example/tiger.js"></script></div>
<script type="text/javascript">
(function () {
"use strict";
function drawExample (example) {
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext("2d");
ctx.clearRect(0, 0, 500, 500);
var c2s = new C2S(500, 500);
var svg = document.getElementById("svg");
if (svg.children.length > 0) {
svg.removeChild(svg.children[0]);
}
example(ctx);
example(c2s);
svg.appendChild(c2s.getSvg());
}
$('#render').on('click', function(event) {
event.preventDefault();
var text = $("#textarea").val();
var drawFunction = new Function("ctx", text);
drawExample(drawFunction);
});
$('#select').on('change', function(event) {
var example = C2S_EXAMPLES[$(this).val()];
drawExample(example);
}).trigger('change');
}());
</script>
</body>
</html>

28
test/testrunner.html Normal file
View File

@ -0,0 +1,28 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title> Canvas2Svg Unit Tests</title>
<link rel="stylesheet" href="../node_modules/mocha/mocha.css">
</head>
<body>
<div id="mocha"></div>
<script src="../node_modules/mocha/mocha.js"></script>
<script src="../node_modules/chai/chai.js"></script>
<script src="../node_modules/resemblejs/resemble.js"></script>
<script src="../canvas2svg.js"></script>
<script type="text/javascript" src="globals.js"></script>
<script>
mocha.setup('bdd');
var should = chai.should();
var expect = chai.expect;
</script>
<!-- examples content is generated by the command `gulp update_examples` -->
<div id="examples"><script type="text/javascript" src="example/arc.js"></script><script type="text/javascript" src="example/arcTo.js"></script><script type="text/javascript" src="example/arcTo2.js"></script><script type="text/javascript" src="example/fillstyle.js"></script><script type="text/javascript" src="example/globalalpha.js"></script><script type="text/javascript" src="example/gradient.js"></script><script type="text/javascript" src="example/linecap.js"></script><script type="text/javascript" src="example/linewidth.js"></script><script type="text/javascript" src="example/rgba.js"></script><script type="text/javascript" src="example/saveandrestore.js"></script><script type="text/javascript" src="example/text.js"></script><script type="text/javascript" src="example/tiger.js"></script></div>
<script src="unit.spec.js"></script>
<script src="example.spec.js"></script>
<script>
mocha.run();
</script>
</body>
</html>

293
test/unit.spec.js Normal file
View File

@ -0,0 +1,293 @@
describe('canvas2svg', function() {
describe('it can be created', function(){
it("with options", function() {
var ctx = new C2S({width:100, height:200, enableMirroring:true});
expect(ctx instanceof C2S).to.equal(true);
expect(ctx.width).to.equal(100);
expect(ctx.height).to.equal(200);
expect(ctx.enableMirroring).to.equal(true);
var ctx2 = new C2S(300,400);
expect(ctx2 instanceof C2S).to.equal(true);
expect(ctx2.width).to.equal(300);
expect(ctx2.height).to.equal(400);
expect(ctx2.enableMirroring).to.equal(false);
});
it("with no options and have defaults", function() {
var ctx = new C2S();
expect(ctx instanceof C2S).to.equal(true);
expect(ctx.width).to.equal(500);
expect(ctx.height).to.equal(500);
expect(ctx.enableMirroring).to.equal(false);
});
it("even if it's called as a function", function() {
//notice the lack of new!
var ctx = C2S({width:100, height:200, enableMirroring:true});
expect(ctx instanceof C2S).to.equal(true);
expect(ctx.width).to.equal(100);
expect(ctx.height).to.equal(200);
expect(ctx.enableMirroring).to.equal(true);
var ctx2 = C2S(300,400);
expect(ctx2 instanceof C2S).to.equal(true);
expect(ctx2.width).to.equal(300);
expect(ctx2.height).to.equal(400);
expect(ctx2.enableMirroring).to.equal(false);
var ctx3 = C2S();
expect(ctx3 instanceof C2S).to.equal(true);
expect(ctx3.width).to.equal(500);
expect(ctx3.height).to.equal(500);
expect(ctx3.enableMirroring).to.equal(false);
});
});
describe("can export to", function() {
it("inline svg", function() {
var ctx = new C2S();
ctx.fillStyle="red";
ctx.fillRect(100,100,100,100);
//svg is of course not attached to the document
var svg = ctx.getSvg();
expect(svg.nodeType).to.equal(1);
expect(svg.nodeName).to.equal("svg");
});
it("serialized svg", function() {
var ctx = new C2S();
ctx.fillStyle="red";
ctx.fillRect(100,100,100,100);
//Standalone SVG doesn't support named entities, which document.createTextNode encodes.
//passing in true will attempt to find all named entities and encode it as a numeric entity.
var string = ctx.getSerializedSvg(true);
expect(typeof string).to.equal("string");
expect(string).to.equal('<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="500" height="500"><defs/><g><rect fill="red" stroke="none" x="100" y="100" width="100" height="100"/></g></svg>');
});
});
describe("with multiple transforms and fill/strokes", function() {
it("creates new groups", function() {
var ctx = new C2S();
ctx.translate(0, 20);
ctx.fillRect(0, 0, 10, 10);
ctx.translate(10, 20);
ctx.fillRect(0, 0, 10, 10);
ctx.translate(20, 20);
ctx.fillRect(0, 0, 10, 10);
var svg = ctx.getSvg();
var firstGroup = svg.querySelector("g");
expect(firstGroup.getAttribute("transform")).to.equal("translate(0,20)");
var secondGroup = firstGroup.querySelector("g");
expect(secondGroup.getAttribute("transform")).to.equal("translate(10,20)");
var thirdGroup = secondGroup.querySelector("g");
expect(thirdGroup.getAttribute("transform")).to.equal("translate(20,20)");
});
it("save and restore still works", function() {
var ctx = new C2S();
ctx.translate(0, 10);
ctx.fillRect(0, 0, 10, 10);
ctx.save();
ctx.translate(40, 40);
ctx.fillRect(0, 0, 10, 10);
ctx.restore();
ctx.translate(0, 10);
ctx.fillRect(0, 0, 10, 10);
var svg = ctx.getSvg();
var firstGroup = svg.querySelector("g");
expect(firstGroup.getAttribute("transform")).to.equal("translate(0,10)");
var secondGroup = firstGroup.childNodes[1];
expect(secondGroup.getAttribute("transform")).to.equal("translate(40,40)");
var thirdGroup = firstGroup.childNodes[2];
expect(thirdGroup.getAttribute("transform")).to.equal("translate(0,10)");
});
});
describe("it will generate ids", function() {
it("that start with a letter", function() {
var ctx = new C2S();
ctx.createRadialGradient(6E1, 6E1, 0.0, 6E1, 6E1, 5E1);
var svg = ctx.getSvg();
var id = svg.children[0].children[0].id;
var test = /^[A-Za-z]/.test(id);
expect(test).to.equal(true);
});
});
describe("will split up rgba", function() {
//while browsers support rgba values for fill/stroke, this is not accepted in visio/illustrator
it("to fill and fill-opacity", function() {
var ctx = new C2S();
ctx.fillStyle="rgba(20,40,50,0.5)";
ctx.fillRect(100,100,100,100);
var svg = ctx.getSvg();
expect(svg.querySelector("rect").getAttribute("fill")).to.equal("rgb(20,40,50)");
expect(svg.querySelector("rect").getAttribute("fill-opacity")).to.equal("0.5");
});
it("to stroke and stroke-opacity", function() {
var ctx = new C2S();
ctx.strokeStyle="rgba(10,20,30,0.4)";
ctx.strokeRect(100,100,100,100);
var svg = ctx.getSvg();
expect(svg.querySelector("rect").getAttribute("stroke")).to.equal("rgb(10,20,30)");
expect(svg.querySelector("rect").getAttribute("stroke-opacity")).to.equal("0.4");
});
});
describe("supports path commands", function() {
it("and moveTo may be called without beginPath, but is not recommended", function() {
var ctx = new C2S();
ctx.moveTo(0,0);
ctx.lineTo(100,100);
ctx.stroke();
});
});
describe("supports text align", function() {
it("not specifying a value defaults to 'start'", function() {
var ctx = new C2S();
ctx.font = "normal 36px Times";
ctx.fillStyle = "#000000";
ctx.fillText("A Text Example", 0, 50);
var svg = ctx.getSvg();
expect(svg.querySelector("text").getAttribute("text-anchor")).to.equal("start");
});
it("assuming ltr, left maps to 'start'", function() {
var ctx = new C2S();
ctx.textAlign = "left";
ctx.font = "normal 36px Times";
ctx.fillStyle = "#000000";
ctx.fillText("A Text Example", 0, 50);
var svg = ctx.getSvg();
expect(svg.querySelector("text").getAttribute("text-anchor")).to.equal("start");
});
it("assuming ltr, right maps to 'end'", function() {
var ctx = new C2S();
ctx.textAlign = "right";
ctx.font = "normal 36px Times";
ctx.fillStyle = "#000000";
ctx.fillText("A Text Example", 0, 50);
var svg = ctx.getSvg();
expect(svg.querySelector("text").getAttribute("text-anchor")).to.equal("end");
});
it("center maps to 'middle'", function() {
var ctx = new C2S();
ctx.textAlign = "center";
ctx.font = "normal 36px Times";
ctx.fillStyle = "#000000";
ctx.fillText("A Text Example", 0, 50);
var svg = ctx.getSvg();
expect(svg.querySelector("text").getAttribute("text-anchor")).to.equal("middle");
});
it("stores the proper values on save and restore", function() {
var ctx = new C2S();
ctx.textAlign = "center";
expect(ctx.textAlign).to.equal("center");
ctx.save();
expect(ctx.textAlign).to.equal("center");
ctx.textAlign = "right";
expect(ctx.textAlign).to.equal("right");
ctx.restore();
expect(ctx.textAlign).to.equal("center");
});
});
describe("supports text baseline", function() {
it("not specifying a value defaults to alphabetic", function() {
var ctx = new C2S();
ctx.font = "normal 36px Times";
ctx.fillStyle = "#000000";
ctx.fillText("A Text Example", 0, 50);
var svg = ctx.getSvg();
expect(svg.querySelector("text").getAttribute("dominant-baseline")).to.equal("alphabetic");
});
it("not specifying a valid value defaults to alphabetic", function() {
var ctx = new C2S();
ctx.font = "normal 36px Times";
ctx.fillStyle = "#000000";
ctx.textBaseline = "werwerwer";
ctx.fillText("A Text Example", 0, 50);
var svg = ctx.getSvg();
expect(svg.querySelector("text").getAttribute("dominant-baseline")).to.equal("alphabetic");
});
it("hanging maps to hanging", function() {
var ctx = new C2S();
ctx.font = "normal 36px Times";
ctx.fillStyle = "#000000";
ctx.textBaseline = "hanging";
ctx.fillText("A Text Example", 0, 50);
var svg = ctx.getSvg();
expect(svg.querySelector("text").getAttribute("dominant-baseline")).to.equal("hanging");
});
it("top maps to text-before-edge", function() {
var ctx = new C2S();
ctx.font = "normal 36px Times";
ctx.fillStyle = "#000000";
ctx.textBaseline = "top";
ctx.fillText("A Text Example", 0, 50);
var svg = ctx.getSvg();
expect(svg.querySelector("text").getAttribute("dominant-baseline")).to.equal("text-before-edge");
});
it("bottom maps to text-after-edge", function() {
var ctx = new C2S();
ctx.font = "normal 36px Times";
ctx.fillStyle = "#000000";
ctx.textBaseline = "bottom";
ctx.fillText("A Text Example", 0, 50);
var svg = ctx.getSvg();
expect(svg.querySelector("text").getAttribute("dominant-baseline")).to.equal("text-after-edge");
});
it("middle maps to central", function() {
var ctx = new C2S();
ctx.font = "normal 36px Times";
ctx.fillStyle = "#000000";
ctx.textBaseline = "middle";
ctx.fillText("A Text Example", 0, 50);
var svg = ctx.getSvg();
expect(svg.querySelector("text").getAttribute("dominant-baseline")).to.equal("central");
});
});
});