Compare commits

...

14 Commits

Author SHA1 Message Date
Lars Jung 631df8abac Update. 5 years ago
Lars Jung bf58382a98 Update. 6 years ago
Lars Jung 86948f725f Update. 6 years ago
Lars Jung ac0af48d8e Update deps. 6 years ago
Lars Jung 761ecaa0c9 Maintenance. 9 years ago
Lars Jung a186351387 Fix minor build issues. 9 years ago
Lars Jung d8e035a60c Push version. 9 years ago
Lars Jung d06051e473 Push version. 9 years ago
Lars Jung 25baa4738e Fix naming issue. 9 years ago
Lars Jung 2979e0411b Fix naming issue. 9 years ago
Lars Jung 0acabd3f05 Maintenance. 9 years ago
Lars Jung 4b4f1181d0 Maintenance. Add utf-8 support. 10 years ago
Lars Jung e8f252f6e1 Maintenance. 11 years ago
Lars Jung 672549f4ac Maintenance. 11 years ago

@ -0,0 +1,24 @@
# editorconfig.org
root = true
[*]
charset = utf-8
indent_style = space
indent_size = 4
end_of_line = lf
insert_final_newline = true
trim_trailing_whitespace = true
[{*.json,*.yml}]
indent_size = 2
[{*.md,*.jade}]
trim_trailing_whitespace = false
[*.svg]
insert_final_newline = false

@ -0,0 +1,4 @@
/build/
/coverage/
/dist/
/node_modules/

@ -0,0 +1,182 @@
---
root: true
env:
es6: true
node: true
parserOptions:
ecmaVersion: 2020
rules:
array-bracket-spacing: [2, never]
arrow-parens: [2, as-needed]
arrow-spacing: 2
block-scoped-var: 2
brace-style: [2, 1tbs, {allowSingleLine: true}]
camelcase: 0
comma-dangle: [2, never]
comma-spacing: [2, {before: false, after: true}]
comma-style: [2, last]
complexity: [1, 16] ###
computed-property-spacing: [2, never]
consistent-return: 2
consistent-this: [2, self]
constructor-super: 2
curly: [2, multi-line]
default-case: 2
dot-location: [2, property]
dot-notation: [2, {allowKeywords: true}]
eol-last: 2
eqeqeq: 2
func-names: 2
func-style: [2, declaration, {allowArrowFunctions: true}]
generator-star-spacing: [2, after]
guard-for-in: 2
handle-callback-err: 2
indent: [2, 4]
key-spacing: [2, {beforeColon: false, afterColon: true}]
keyword-spacing: [2, {before: true, after: true}]
linebreak-style: [2, unix]
max-depth: [1, 4]
max-len: [0, 80, 4]
max-nested-callbacks: [1, 3]
max-params: [1, 16] ###
max-statements: [1, 32] ###
new-cap: 0
new-parens: 2
newline-after-var: 0
no-alert: 2
no-array-constructor: 2
no-bitwise: 2
no-caller: 2
no-catch-shadow: 2
no-class-assign: 2
no-cond-assign: 2
no-console: 0 ###
no-const-assign: 2
no-constant-condition: 1
no-continue: 0
no-control-regex: 2
no-debugger: 2
no-delete-var: 2
no-div-regex: 2
no-dupe-args: 2
no-dupe-class-members: 2
no-dupe-keys: 2
no-duplicate-case: 2
no-else-return: 1
no-empty: 2
no-empty-character-class: 2
no-empty-pattern: 2
no-eq-null: 2
no-eval: 2
no-ex-assign: 2
no-extend-native: 1
no-extra-bind: 2
no-extra-boolean-cast: 2
no-extra-parens: 1
no-extra-semi: 2
no-fallthrough: 2
no-floating-decimal: 2
no-func-assign: 2
no-implicit-coercion: [2, {boolean: false, number: true, string: true}]
no-implied-eval: 2
no-inline-comments: 0
no-inner-declarations: [2, functions]
no-invalid-regexp: 2
no-invalid-this: 2
no-irregular-whitespace: 2
no-iterator: 2
no-label-var: 2
no-labels: 2
no-lone-blocks: 2
no-lonely-if: 2
no-loop-func: 1
no-magic-numbers: 0
no-mixed-requires: [2, false]
no-mixed-spaces-and-tabs: [2, false]
no-multi-spaces: 2
no-multi-str: 2
no-multiple-empty-lines: [2, {max: 4}]
no-native-reassign: 1
no-negated-in-lhs: 2
no-nested-ternary: 0
no-new: 2
no-new-func: 2
no-new-object: 2
no-new-require: 2
no-new-wrappers: 2
no-obj-calls: 2
no-octal: 2
no-octal-escape: 2
no-param-reassign: 0
no-path-concat: 2
no-plusplus: 2
no-process-env: 2
no-process-exit: 2
no-proto: 2
no-redeclare: 2
no-regex-spaces: 2
no-restricted-modules: 2
no-return-assign: 2
no-script-url: 2
no-self-compare: 2
no-sequences: 2
no-shadow: 2
no-shadow-restricted-names: 2
no-spaced-func: 2
no-sparse-arrays: 2
no-sync: 0
no-ternary: 0
no-this-before-super: 2
no-throw-literal: 1
no-trailing-spaces: 2
no-undef: 2
no-undef-init: 2
no-undefined: 0
no-underscore-dangle: 0
no-unexpected-multiline: 2
no-unneeded-ternary: 2
no-unreachable: 2
no-useless-call: 2
no-useless-concat: 2
no-unused-expressions: 2
no-unused-vars: [1, {vars: all, args: after-used}]
no-use-before-define: 2
no-var: 2
no-void: 2
no-warning-comments: [1, {terms: [todo, fixme, xxx], location: start}]
no-with: 2
object-curly-spacing: [2, never]
object-shorthand: [2, always]
one-var: [2, never]
operator-assignment: [2, always]
operator-linebreak: [2, after]
padded-blocks: [2, never]
prefer-arrow-callback: 2
prefer-const: 1
prefer-reflect: 1
prefer-spread: 2
prefer-template: 0 ###
quote-props: [2, as-needed]
quotes: [2, single, avoid-escape]
radix: 2
require-yield: 2
semi: 2
semi-spacing: [2, {before: false, after: true}]
sort-vars: 0
space-before-blocks: [2, always]
space-before-function-paren: [2, {anonymous: always, named: never}]
space-in-parens: [2, never]
space-infix-ops: 2
space-unary-ops: [2, {words: true, nonwords: false}]
spaced-comment: [2, always]
strict: [2, never]
use-isnan: 2
valid-jsdoc: 2
valid-typeof: 2
vars-on-top: 0
wrap-iife: [2, outside]
wrap-regex: 2
yoda: [2, never, {exceptRange: true}]

10
.gitignore vendored

@ -1,5 +1,5 @@
bower_components
build
local
node_modules
/build/
/coverage/
/local/
/node_modules/
/npm-debug.log

@ -1,14 +1,16 @@
# jQuery.qrcode
[![web][web-img]][web] [![GitHub][github-img]][github] [![bower][bower-img]][github]
[![license][license-img]][github] [![web][web-img]][web] [![github][github-img]][github]
jQuery plugin to dynamically generate QR codes. Uses [QR Code Generator][qrcode] (MIT).
There is a newer lib named [kjua][kjua] that works in all modern browsers
with crisp codes on all devices.
## License
The MIT License (MIT)
Copyright (c) 2014 Lars Jung (http://larsjung.de)
Copyright (c) 2020 Lars Jung (https://larsjung.de)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
@ -29,11 +31,12 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
[web]: http://larsjung.de/qrcode/
[web]: https://larsjung.de/qrcode/
[github]: https://github.com/lrsjng/jquery-qrcode
[web-img]: http://img.shields.io/badge/web-larsjung.de/qrcode-a0a060.svg?style=flat
[github-img]: http://img.shields.io/badge/GitHub-lrsjng/jquery--qrcode-a0a060.svg?style=flat
[bower-img]: http://img.shields.io/badge/bower-lrsjng/jquery--qrcode-a0a060.svg?style=flat
[license-img]: https://img.shields.io/badge/license-MIT-a0a060.svg?style=flat-square
[web-img]: https://img.shields.io/badge/web-larsjung.de/jquery--qrcode-a0a060.svg?style=flat-square
[github-img]: https://img.shields.io/badge/github-lrsjng/jquery--qrcode-a0a060.svg?style=flat-square
[qrcode]: https://github.com/kazuhikoarase/qrcode-generator
[kjua]: https://larsjung.de/kjua/

@ -1,27 +0,0 @@
{
"name": "jquery-qrcode",
"version": "0.10.0",
"description": "generate QR codes dynamically",
"homepage": "http://larsjung.de/jquery-qrcode/",
"authors": [
"Lars Jung <lrsjng@gmail.com> (http://larsjung.de)"
],
"license": "MIT",
"main": "dist/jquery.qrcode.js",
"keywords": [
"jquery",
"javascript",
"qrcode"
],
"ignore": [
"**/.*",
"bower_components",
"build",
"local",
"makefile.js",
"node_modules",
"src",
"test",
"tests"
]
}

2817
dist/jquery-qrcode.js vendored

File diff suppressed because it is too large Load Diff

File diff suppressed because one or more lines are too long

1885
dist/jquery.qrcode.js vendored

File diff suppressed because it is too large Load Diff

File diff suppressed because one or more lines are too long

@ -0,0 +1,66 @@
const {resolve, join} = require('path');
const {ghu, pug, jszip, mapfn, read, remove, webpack, uglify, wrap, write} = require('ghu');
const overwrite = arg => write(arg, {overwrite: true});
const NAME = 'jquery-qrcode';
const ROOT = resolve(__dirname);
const SRC = join(ROOT, 'src');
const BUILD = join(ROOT, 'build');
const DIST = join(ROOT, 'dist');
ghu.defaults('release');
ghu.before(runtime => {
runtime.pkg = Object.assign({}, require('./package.json'));
runtime.comment = `${runtime.pkg.name} v${runtime.pkg.version} - ${runtime.pkg.homepage}`;
runtime.commentJs = `/*! ${runtime.comment} */\n`;
console.log(runtime.comment);
});
ghu.task('clean', () => {
return remove(`${BUILD}, ${DIST}`);
});
ghu.task('build:scripts', runtime => {
return read(`${SRC}/${NAME}.js`)
.then(webpack(webpack.cfg_umd(NAME, [SRC])))
.then(wrap(runtime.commentJs))
.then(overwrite(`${DIST}/${NAME}.js`))
.then(overwrite(`${BUILD}/${NAME}-${runtime.pkg.version}.js`))
.then(uglify())
.then(wrap(runtime.commentJs))
.then(overwrite(`${DIST}/${NAME}.min.js`))
.then(overwrite(`${BUILD}/${NAME}-${runtime.pkg.version}.min.js`));
});
ghu.task('build:other', runtime => {
return Promise.all([
read(`${ROOT}/*.md`)
.then(overwrite(mapfn.p(ROOT, BUILD))),
read(`${SRC}/demo/*.pug`)
.then(pug({pkg: runtime.pkg}))
.then(overwrite(mapfn.p(SRC, BUILD).s('.pug', ''))),
read(`${SRC}/demo/*.js`)
.then(webpack(webpack.cfg([SRC])))
.then(uglify())
.then(wrap(runtime.commentJs))
.then(overwrite(mapfn.p(SRC, BUILD))),
read(`${SRC}/demo/*, !**/*.pug, !**/*.js`)
.then(overwrite(mapfn.p(SRC, BUILD))),
read(`${ROOT}/node_modules/jquery/dist/jquery.min.js`)
.then(overwrite(`${BUILD}/demo/jquery.min.js`))
]);
});
ghu.task('build', ['build:scripts', 'build:other']);
ghu.task('zip', ['build'], runtime => {
return read(`${BUILD}/**/*`)
.then(jszip({dir: BUILD, level: 9}))
.then(overwrite(`${BUILD}/${NAME}-${runtime.pkg.version}.zip`));
});
ghu.task('release', ['clean', 'zip']);

@ -1,92 +0,0 @@
/*jshint node: true */
'use strict';
module.exports = function (make) {
var path = require('path'),
pkg = require('./package.json'),
$ = make.fQuery,
root = path.resolve(__dirname),
src = path.join(root, 'src'),
dist = path.join(root, 'dist'),
build = path.join(root, 'build');
make.version('=0.11.0');
make.defaults('release');
make.target('clean', [], 'delete build folder').sync(function () {
$.DELETE(build);
$.DELETE(dist);
});
make.target('lint', [], 'lint all JavaScript files with JSHint').sync(function () {
var options = {
// Enforcing Options
bitwise: true,
curly: true,
eqeqeq: true,
forin: true,
latedef: true,
newcap: true,
noempty: true,
plusplus: true,
trailing: true,
undef: true,
// Environments
browser: true
},
global = {
'jQuery': true,
'qrcode': true
};
$(src + ': jquery.qrcode.js, demo/scripts.js').log(-3)
.jshint(options, global);
});
make.target('build', ['clean', 'lint'], 'build all files').sync(function () {
var header = '/* ' + pkg.displayName + ' ' + pkg.version + ' - ' + pkg.homepage + ' - uses //github.com/kazuhikoarase/qrcode-generator (MIT) */\n';
var env = {pkg: pkg};
$(src + ': jquery.qrcode.js')
.includify()
.handlebars(env)
.wrap(header)
.WRITE($.map.p(src, dist))
.WRITE($.map.p(src, build).s('.js', '-' + pkg.version + '.js'))
.uglifyjs()
.wrap(header)
.WRITE($.map.p(src, dist).s('.js', '.min.js'))
.WRITE($.map.p(src, build).s('.js', '-' + pkg.version + '.min.js'));
$(src + ': **, ! *.js')
.handlebars(env)
.WRITE($.map.p(src, build));
$(root + ': *.md')
.handlebars(env)
.WRITE($.map.p(root, build));
});
make.target('release', ['build'], 'create a zipball').async(function (done, fail) {
$(build + ': **').shzip({
target: path.join(build, pkg.name + '-' + pkg.version + '.zip'),
dir: build,
callback: done
});
});
};

5805
package-lock.json generated

File diff suppressed because it is too large Load Diff

@ -1,14 +1,26 @@
{
"name": "jquery-qrcode",
"displayName": "jQuery.qrcode",
"version": "0.10.0",
"description": "generate QR codes dynamically",
"homepage": "http://larsjung.de/jquery-qrcode/",
"bugs": "https://github.com/lrsjng/jquery-qrcode/issues",
"author": "Lars Jung <lrsjng@gmail.com> (http://larsjung.de)",
"title": "jQuery.qrcode",
"version": "0.18.0",
"description": "Generate QR codes dynamically.",
"homepage": "https://larsjung.de/jquery-qrcode/",
"author": "Lars Jung <lrsjng@gmail.com> (https://larsjung.de)",
"license": "MIT",
"scripts": {
"lint": "eslint .",
"build": "node ghu release",
"precommit": "npm run -s lint && npm run -s build"
},
"repository": {
"type": "git",
"url": "https://github.com/lrsjng/jquery-qrcode.git"
},
"devDependencies": {
"@babel/core": "7.10.5",
"@babel/preset-env": "7.10.4",
"eslint": "7.5.0",
"ghu": "0.26.0",
"jquery": "3.5.1",
"qrcode-generator": "1.4.4"
}
}

Binary file not shown.

Before

Width:  |  Height:  |  Size: 13 KiB

After

Width:  |  Height:  |  Size: 1.8 KiB

@ -1,294 +0,0 @@
/*
html5slider - a JS implementation of <input type=range> for Firefox 16 and up
https://github.com/fryn/html5slider
Copyright (c) 2010-2013 Frank Yan, <http://frankyan.com>
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() {
// test for native support
var test = document.createElement('input');
try {
test.type = 'range';
if (test.type == 'range')
return;
} catch (e) {
return;
}
// test for required property support
test.style.background = 'linear-gradient(red, red)';
if (!test.style.backgroundImage || !('MozAppearance' in test.style))
return;
var scale;
var isMac = navigator.platform == 'MacIntel';
var thumb = {
radius: isMac ? 9 : 6,
width: isMac ? 22 : 12,
height: isMac ? 16 : 20
};
var track = 'linear-gradient(transparent ' + (isMac ?
'6px, #999 6px, #999 7px, #ccc 8px, #bbb 9px, #bbb 10px, transparent 10px' :
'9px, #999 9px, #bbb 10px, #fff 11px, transparent 11px') +
', transparent)';
var styles = {
'min-width': thumb.width + 'px',
'min-height': thumb.height + 'px',
'max-height': thumb.height + 'px',
padding: '0 0 ' + (isMac ? '2px' : '1px'),
border: 0,
'border-radius': 0,
cursor: 'default',
'text-indent': '-999999px' // -moz-user-select: none; breaks mouse capture
};
var options = {
attributes: true,
attributeFilter: ['min', 'max', 'step', 'value']
};
var onInput = document.createEvent('HTMLEvents');
onInput.initEvent('input', true, false);
var onChange = document.createEvent('HTMLEvents');
onChange.initEvent('change', true, false);
if (document.readyState == 'loading')
document.addEventListener('DOMContentLoaded', initialize, true);
else
initialize();
addEventListener('pageshow', recreate, true);
function initialize() {
// create initial sliders
recreate();
// create sliders on-the-fly
new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
if (mutation.addedNodes)
Array.forEach(mutation.addedNodes, function(node) {
if (!(node instanceof Element))
;
else if (node.childElementCount)
Array.forEach(node.querySelectorAll('input[type=range]'), check);
else if (node.mozMatchesSelector('input[type=range]'))
check(node);
});
});
}).observe(document, { childList: true, subtree: true });
}
function recreate() {
Array.forEach(document.querySelectorAll('input[type=range]'), check);
}
function check(input) {
if (input.type != 'range')
transform(input);
}
function transform(slider) {
var isValueSet, areAttrsSet, isUI, isClick, prevValue, rawValue, prevX;
var min, max, step, range, value = slider.value;
// lazily create shared slider affordance
if (!scale) {
scale = document.body.appendChild(document.createElement('hr'));
style(scale, {
'-moz-appearance': isMac ? 'scale-horizontal' : 'scalethumb-horizontal',
display: 'block',
visibility: 'visible',
opacity: 1,
position: 'fixed',
top: '-999999px'
});
document.mozSetImageElement('__sliderthumb__', scale);
}
// reimplement value and type properties
var getValue = function() { return '' + value; };
var setValue = function setValue(val) {
value = '' + val;
isValueSet = true;
draw();
delete slider.value;
slider.value = value;
slider.__defineGetter__('value', getValue);
slider.__defineSetter__('value', setValue);
};
slider.__defineGetter__('value', getValue);
slider.__defineSetter__('value', setValue);
Object.defineProperty(slider, 'type', {
get: function() { return 'range'; }
});
// sync properties with attributes
['min', 'max', 'step'].forEach(function(name) {
if (slider.hasAttribute(name))
areAttrsSet = true;
Object.defineProperty(slider, name, {
get: function() {
return this.hasAttribute(name) ? this.getAttribute(name) : '';
},
set: function(val) {
val === null ?
this.removeAttribute(name) :
this.setAttribute(name, val);
}
});
});
// initialize slider
slider.readOnly = true;
style(slider, styles);
update();
new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
if (mutation.attributeName != 'value') {
update();
areAttrsSet = true;
}
// note that value attribute only sets initial value
else if (!isValueSet) {
value = slider.getAttribute('value');
draw();
}
});
}).observe(slider, options);
slider.addEventListener('mousedown', onDragStart, true);
slider.addEventListener('keydown', onKeyDown, true);
slider.addEventListener('focus', onFocus, true);
slider.addEventListener('blur', onBlur, true);
function onDragStart(e) {
isClick = true;
setTimeout(function() { isClick = false; }, 0);
if (e.button || !range)
return;
var width = parseFloat(getComputedStyle(this).width);
var multiplier = (width - thumb.width) / range;
if (!multiplier)
return;
// distance between click and center of thumb
var dev = e.clientX - this.getBoundingClientRect().left - thumb.width / 2 -
(value - min) * multiplier;
// if click was not on thumb, move thumb to click location
if (Math.abs(dev) > thumb.radius) {
isUI = true;
this.value -= -dev / multiplier;
}
rawValue = value;
prevX = e.clientX;
this.addEventListener('mousemove', onDrag, true);
this.addEventListener('mouseup', onDragEnd, true);
}
function onDrag(e) {
var width = parseFloat(getComputedStyle(this).width);
var multiplier = (width - thumb.width) / range;
if (!multiplier)
return;
rawValue += (e.clientX - prevX) / multiplier;
prevX = e.clientX;
isUI = true;
this.value = rawValue;
}
function onDragEnd() {
this.removeEventListener('mousemove', onDrag, true);
this.removeEventListener('mouseup', onDragEnd, true);
slider.dispatchEvent(onInput);
slider.dispatchEvent(onChange);
}
function onKeyDown(e) {
if (e.keyCode > 36 && e.keyCode < 41) { // 37-40: left, up, right, down
onFocus.call(this);
isUI = true;
this.value = value + (e.keyCode == 38 || e.keyCode == 39 ? step : -step);
}
}
function onFocus() {
if (!isClick)
this.style.boxShadow = !isMac ? '0 0 0 2px #fb0' :
'inset 0 0 20px rgba(0,127,255,.1), 0 0 1px rgba(0,127,255,.4)';
}
function onBlur() {
this.style.boxShadow = '';
}
// determines whether value is valid number in attribute form
function isAttrNum(value) {
return !isNaN(value) && +value == parseFloat(value);
}
// validates min, max, and step attributes and redraws
function update() {
min = isAttrNum(slider.min) ? +slider.min : 0;
max = isAttrNum(slider.max) ? +slider.max : 100;
if (max < min)
max = min > 100 ? min : 100;
step = isAttrNum(slider.step) && slider.step > 0 ? +slider.step : 1;
range = max - min;
draw(true);
}
// recalculates value property
function calc() {
if (!isValueSet && !areAttrsSet)
value = slider.getAttribute('value');
if (!isAttrNum(value))
value = (min + max) / 2;;
// snap to step intervals (WebKit sometimes does not - bug?)
value = Math.round((value - min) / step) * step + min;
if (value < min)
value = min;
else if (value > max)
value = min + ~~(range / step) * step;
}
// renders slider using CSS background ;)
function draw(attrsModified) {
calc();
var wasUI = isUI;
isUI = false;
if (wasUI && value != prevValue)
slider.dispatchEvent(onInput);
if (!attrsModified && value == prevValue)
return;
prevValue = value;
var position = range ? (value - min) / range * 100 : 0;
var bg = '-moz-element(#__sliderthumb__) ' + position + '% no-repeat, ';
style(slider, { background: bg + track });
}
}
function style(element, styles) {
for (var prop in styles)
element.style.setProperty(prop, styles[prop], 'important');
}
})();

@ -1,93 +0,0 @@
<!DOCTYPE html>
<html class="no-js no-browser" lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>{{pkg.displayName}} {{pkg.version}} · Demo</title>
<meta name="description" content="demo for the jQuery plug in jQuery.qrcode (http://larsjung.de/qrcode/)">
<meta name="author" content="Lars Jung">
<meta name="viewport" content="width=device-width">
<link rel="author" href="http://plus.google.com/106403733398479106535">
<link rel="shortcut icon" href="icon-16.ico">
<link rel="apple-touch-icon" href="icon-48.png" type="image/png">
<link href='http://fonts.googleapis.com/css?family=Ubuntu:400,700' rel='stylesheet'>
<link href='styles.css' rel='stylesheet'>
<script src="jquery-1.10.2.js"></script>
<script src="../jquery.qrcode-{{pkg.version}}.js"></script>
<script src="ff-range.js"></script>
<script src="scripts.js"></script>
</head>
<body>
<div id="container"></div>
<div class="control left">
<a id="banner" href="http://larsjung.de/qrcode/">{{pkg.displayName}} {{pkg.version}}</a>
<hr/>
<label for="render">RENDER MODE</label>
<select id="render">
<option value="canvas" selected="selected">Canvas</option>
<option value="image">Image</option>
<option value="div">DIV</option>
</select>
<hr/>
<label for="size">SIZE:</label>
<input id="size" type="range" value="400" min="100" max="1000" step="50" />
<label for="fill">FILL</label>
<input id="fill" type="color" value="#333333" />
<label for="background">BACKGROUND</label>
<input id="background" type="color" value="#ffffff" />
<label for="text">CONTENT</label>
<textarea id="text">http://larsjung.de/qrcode/</textarea>
<hr/>
<label for="minversion">MIN VERSION:</label>
<input id="minversion" type="range" value="6" min="1" max="10" step="1" />
<label for="eclevel">ERROR CORRECTION LEVEL</label>
<select id="eclevel">
<option value="L">L - Low (7%)</option>
<option value="M">M - Medium (15%)</option>
<option value="Q">Q - Quartile (25%)</option>
<option value="H" selected="selected">H - High (30%)</option>
</select>
<label for="quiet">QUIET ZONE:</label>
<input id="quiet" type="range" value="1" min="0" max="4" step="1" />
<label for="radius">CORNER RADIUS (not in Opera):</label>
<input id="radius" type="range" value="50" min="0" max="50" step="10" />
<!-- <hr/> -->
<!-- <a id="download" download="qrcode.png">DOWNLOAD</a> -->
</div>
<div class="control right">
<label for="mode">MODE</label>
<select id="mode">
<option value="0">0 - Normal</option>
<option value="1">1 - Label-Strip</option>
<option value="2" selected="selected">2 - Label-Box</option>
<option value="3">3 - Image-Strip</option>
<option value="4">4 - Image-Box</option>
</select>
<hr/>
<label for="msize">SIZE:</label>
<input id="msize" type="range" value="11" min="0" max="40" step="1" />
<label for="mposx">POS X:</label>
<input id="mposx" type="range" value="50" min="0" max="100" step="1" />
<label for="mposy">POS Y:</label>
<input id="mposy" type="range" value="50" min="0" max="100" step="1" />
<hr/>
<label for="label">LABEL</label>
<input id="label" type="text" value="jQuery.qrcode" />
<label for="font">FONT NAME</label>
<input id="font" type="text" value="Ubuntu" />
<label for="fontcolor">FONT COLOR:</label>
<input id="fontcolor" type="color" value="#ff9818" />
<hr/>
<label for="image">IMAGE</label>
<input id="image" type="file" />
</div>
<img id="img-buffer" src="dummy.png" />
</body>
</html>

@ -0,0 +1,80 @@
doctype html
html(lang='en')
head
meta(charset='utf-8')
title #{pkg.title} #{pkg.version} Demo
meta(name='description', content=`Demo for ${pkg.title} (${pkg.homepage}).`)
meta(name='viewport', content='width=device-width, initial-scale=1')
link(href='styles.css', rel='stylesheet')
link(href='//fonts.googleapis.com/css2?family=Ubuntu+Mono:wght@400;700&display=swap' rel='stylesheet')
script(src='jquery.min.js')
script(src=`../jquery-qrcode-${pkg.version}.js`)
script(src='scripts.js')
body
div#container
div.control.left
a#banner(href=pkg.homepage) #{pkg.title} #{pkg.version}
hr
label(for='render') RENDER MODE
select#render
option(value='canvas', selected='selected') canvas
option(value='image') image
option(value='div') div
hr
label(for='size') SIZE:
input#size(type='range', value='400', min='100', max='1000', step='50')
label(for='fill') FILL
input#fill(type='color', value='#333333')
label(for='background') BACKGROUND
input#background(type='color', value='#ffffff')
label(for='text') CONTENT
textarea#text #{pkg.homepage}
hr
label(for='minversion') MIN VERSION:
input#minversion(type='range', value='6', min='1', max='10', step='1')
label(for='eclevel') ERROR CORRECTION LEVEL
select#eclevel
option(value='L') L - Low (7%)
option(value='M') M - Medium (15%)
option(value='Q') Q - Quartile (25%)
option(value='H', selected='selected') H - High (30%)
label(for='quiet') QUIET ZONE:
input#quiet(type='range', value='1', min='0', max='4', step='1')
label(for='radius') CORNER RADIUS:
input#radius(type='range', value='50', min='0', max='50', step='10')
div.control.right
label(for='mode') MODE
select#mode
option(value='0') 0 - Normal
option(value='1') 1 - Label-Strip
option(value='2', selected='selected') 2 - Label-Box
option(value='3') 3 - Image-Strip
option(value='4') 4 - Image-Box
hr
label(for='msize') SIZE:
input#msize(type='range', value='11', min='0', max='40', step='1')
label(for='mposx') POS X:
input#mposx(type='range', value='50', min='0', max='100', step='1')
label(for='mposy') POS Y:
input#mposy(type='range', value='50', min='0', max='100', step='1')
hr
label(for='label') LABEL
input#label(type='text', value=pkg.title)
label(for='font') FONT NAME
input#font(type='text', value='Ubuntu Mono')
label(for='fontcolor') FONT COLOR
input#fontcolor(type='color', value='#ff9818')
hr
label(for='image') IMAGE
input#image(type='file')
img#img-buffer(src='dummy.png')

File diff suppressed because it is too large Load Diff

@ -1,103 +1,81 @@
(function ($) {
'use strict';
var isOpera = Object.prototype.toString.call(window.opera) === '[object Opera]',
guiValuePairs = [
["size", "px"],
["minversion", ""],
["quiet", " modules"],
["radius", "%"],
["msize", "%"],
["mposx", "%"],
["mposy", "%"]
],
updateGui = function () {
$.each(guiValuePairs, function (idx, pair) {
var $label = $('label[for="' + pair[0] + '"]');
$label.text($label.text().replace(/:.*/, ': ' + $('#' + pair[0]).val() + pair[1]));
});
},
updateQrCode = function () {
var options = {
render: $("#render").val(),
ecLevel: $("#eclevel").val(),
minVersion: parseInt($("#minversion").val(), 10),
fill: $("#fill").val(),
background: $("#background").val(),
// fill: $("#img-buffer")[0],
text: $("#text").val(),
size: parseInt($("#size").val(), 10),
radius: parseInt($("#radius").val(), 10) * 0.01,
quiet: parseInt($("#quiet").val(), 10),
mode: parseInt($("#mode").val(), 10),
mSize: parseInt($("#msize").val(), 10) * 0.01,
mPosX: parseInt($("#mposx").val(), 10) * 0.01,
mPosY: parseInt($("#mposy").val(), 10) * 0.01,
label: $("#label").val(),
fontname: $("#font").val(),
fontcolor: $("#fontcolor").val(),
image: $("#img-buffer")[0]
};
$("#container").empty().qrcode(options);
},
update = function () {
updateGui();
updateQrCode();
},
onImageInput = function () {
var input = $("#image")[0];
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (event) {
$("#img-buffer").attr("src", event.target.result);
$("#mode").val("4");
setTimeout(update, 250);
};
reader.readAsDataURL(input.files[0]);
}
},
download = function (event) {
var data = $("#container canvas")[0].toDataURL('image/png');
$("#download").attr("href", data);
};
$(function () {
if (isOpera) {
$('html').addClass('opera');
$('#radius').prop('disabled', true);
}
$("#download").on("click", download);
$("#image").on('change', onImageInput);
$("input, textarea, select").on("input change", update);
$(window).load(update);
update();
});
}(jQuery));
const WIN = global.window;
const JQ = WIN.jQuery;
const GUI_VALUE_PAIRS = [
['size', 'px'],
['minversion', ''],
['quiet', ' modules'],
['radius', '%'],
['msize', '%'],
['mposx', '%'],
['mposy', '%']
];
const update_gui = () => {
JQ.each(GUI_VALUE_PAIRS, (idx, pair) => {
const $label = JQ('label[for="' + pair[0] + '"]');
$label.text($label.text().replace(/:.*/, ': ' + JQ('#' + pair[0]).val() + pair[1]));
});
};
const update_qrcode = () => {
const options = {
render: JQ('#render').val(),
ecLevel: JQ('#eclevel').val(),
minVersion: parseInt(JQ('#minversion').val(), 10),
fill: JQ('#fill').val(),
background: JQ('#background').val(),
text: JQ('#text').val(),
size: parseInt(JQ('#size').val(), 10),
radius: parseInt(JQ('#radius').val(), 10) * 0.01,
quiet: parseInt(JQ('#quiet').val(), 10),
mode: parseInt(JQ('#mode').val(), 10),
mSize: parseInt(JQ('#msize').val(), 10) * 0.01,
mPosX: parseInt(JQ('#mposx').val(), 10) * 0.01,
mPosY: parseInt(JQ('#mposy').val(), 10) * 0.01,
label: JQ('#label').val(),
fontname: JQ('#font').val(),
fontcolor: JQ('#fontcolor').val(),
image: JQ('#img-buffer')[0]
};
// options.fill = JQ('#img-buffer')[0];
// options.fill = 'rgba(255,0,0,0.5)';
// options.background = JQ('#img-buffer')[0];
// options.background = 'rgba(255,0,0,0.5)';
JQ('#container').empty().qrcode(options);
};
const update = () => {
update_gui();
update_qrcode();
};
const on_img_input = () => {
const input = JQ('#image')[0];
if (input.files && input.files[0]) {
const reader = new WIN.FileReader();
reader.onload = event => {
JQ('#img-buffer').attr('src', event.target.result);
JQ('#mode').val('4');
setTimeout(update, 250);
};
reader.readAsDataURL(input.files[0]);
}
};
const init = () => {
JQ('#image').on('change', on_img_input);
JQ('input, textarea, select').on('input change', update);
JQ(WIN).on('load', update);
update();
};
JQ(init);

@ -1,112 +1,108 @@
* {
margin: 0;
padding: 0;
}
body {
font-family: Ubuntu;
margin: 0;
padding: 0;
text-align: center;
background: repeat url("back.png");
font-family: 'Ubuntu Mono', 'monospace';
text-align: center;
background: repeat url('back.png');
}
#banner {
display: block;
text-decoration: none;
color: rgb(29, 119, 194);
padding: 12px 0 0;
text-align: center;
display: block;
text-decoration: none;
color: rgb(29, 119, 194);
padding: 12px 0 0;
text-align: center;
}
#banner:hover {
color: #333;
color: #333;
}
#container {
display: inline-block;
margin: 20px auto;
box-shadow: 0 0 16px rgba(0,0,0,0.5);
display: inline-block;
margin: 20px auto;
box-shadow: 0 0 16px rgba(0,0,0,0.5);
-webkit-print-color-adjust: exact;
}
#container > * {
display: block;
display: block;
}
.control {
position: absolute;
background-color: #f8f8f8;
top: 0;
width: 190px;
box-shadow: 0 0 32px rgba(0,0,0,0.5);
overflow: hidden;
text-align: left;
position: absolute;
background-color: #f8f8f8;
top: 0;
width: 190px;
box-shadow: 0 0 32px rgba(0,0,0,0.5);
overflow: hidden;
text-align: left;
}
.control.left {
left: 0;
left: 0;
}
.control.right {
right: 0;
right: 0;
}
hr {
margin: 12px 0 0;
padding: 0;
border: none;
height: 1px;
background-color: rgba(0,0,0,0.1);
margin: 12px 0 0;
padding: 0;
border: none;
height: 1px;
background-color: rgba(0,0,0,0.1);
}
label {
font-size: 10px;
color: #bbb;
padding: 12px 4px 0 4px;
}
html.opera label[for="radius"] {
color: #e55;
}
#download {
text-align: center;
font-weight: bold;
text-decoration: none;
display: block;
color: #555;
background-color: #ddd;
margin: 4px;
padding: 8px 0;
border: 1px solid #ddd;
cursor: pointer;
display: block;
font-size: 12px;
color: #555;
padding: 12px 4px 4px 4px;
}
input, textarea, select {
font-family: Ubuntu;
display: block;
background-color: #fff;
margin: 2px;
padding: 0 2px;
border: 1px solid #ddd;
width: 180px;
height: 22px;
font-family: 'Ubuntu Mono', 'monospace';
display: block;
background-color: #fff;
margin: 2px;
padding: 0 2px;
border: 1px solid #ddd;
width: 180px;
height: 22px;
}
#text {
height: 48px;
height: 48px;
}
#img-buffer {
display: none;
display: none;
}
input[type="range"] {
-webkit-appearance: none;
cursor: pointer;
input[type='range'] {
-webkit-appearance: none;
cursor: pointer;
}
input::-webkit-slider-thumb {
-webkit-appearance: none;
width: 16px;
height: 16px;
border-radius: 3px;
background-image: -webkit-gradient(linear, left top, left bottom, color-stop(0, #aaa), color-stop(1, #aaa) );
-webkit-appearance: none;
width: 16px;
height: 16px;
border-radius: 3px;
background-image: -webkit-gradient(linear, left top, left bottom, color-stop(0, #aaa), color-stop(1, #aaa));
}
@media print {
#container {
box-shadow: none;
}
.control {
display: none;
}
}

415
src/jquery-qrcode.js vendored

@ -0,0 +1,415 @@
const WIN = window; // eslint-disable-line
const JQ = WIN.jQuery;
const is_img_el = x => x && typeof x.tagName === 'string' && x.tagName.toUpperCase() === 'IMG';
// Wrapper for the original QR code generator.
const create_qrcode = (text, level, version, quiet) => {
const qr = {};
const qr_gen = require('qrcode-generator');
qr_gen.stringToBytes = qr_gen.stringToBytesFuncs['UTF-8'];
const vqr = qr_gen(version, level);
vqr.addData(text);
vqr.make();
quiet = quiet || 0;
const module_count = vqr.getModuleCount();
const quiet_module_count = module_count + 2 * quiet;
const is_dark = (row, col) => {
row -= quiet;
col -= quiet;
return row >= 0 && row < module_count && col >= 0 && col < module_count && vqr.isDark(row, col);
};
const add_blank = (l, t, r, b) => {
const prev_is_dark = qr.is_dark;
const module_size = 1 / quiet_module_count;
qr.is_dark = (row, col) => {
const ml = col * module_size;
const mt = row * module_size;
const mr = ml + module_size;
const mb = mt + module_size;
return prev_is_dark(row, col) && (l > mr || ml > r || t > mb || mt > b);
};
};
qr.text = text;
qr.level = level;
qr.version = version;
qr.module_count = quiet_module_count;
qr.is_dark = is_dark;
qr.add_blank = add_blank;
return qr;
};
// Returns a minimal QR code for the given text starting with version `min_ver`.
// Returns `undefined` if `text` is too long to be encoded in `max_ver`.
const create_min_qrcode = (text, level, min_ver, max_ver, quiet) => {
min_ver = Math.max(1, min_ver || 1);
max_ver = Math.min(40, max_ver || 40);
for (let ver = min_ver; ver <= max_ver; ver += 1) {
try {
return create_qrcode(text, level, ver, quiet);
} catch (err) {/* empty */}
}
return undefined;
};
const draw_background_label = (qr, ctx, settings) => {
const size = settings.size;
const font = 'bold ' + settings.mSize * size + 'px ' + settings.fontname;
const tmp_ctx = JQ('<canvas/>')[0].getContext('2d');
tmp_ctx.font = font;
const w = tmp_ctx.measureText(settings.label).width;
const sh = settings.mSize;
const sw = w / size;
const sl = (1 - sw) * settings.mPosX;
const st = (1 - sh) * settings.mPosY;
const sr = sl + sw;
const sb = st + sh;
const pad = 0.01;
if (settings.mode === 1) {
// Strip
qr.add_blank(0, st - pad, size, sb + pad);
} else {
// Box
qr.add_blank(sl - pad, st - pad, sr + pad, sb + pad);
}
ctx.fillStyle = settings.fontcolor;
ctx.font = font;
ctx.fillText(settings.label, sl * size, st * size + 0.75 * settings.mSize * size);
};
const draw_background_img = (qr, ctx, settings) => {
const size = settings.size;
const w = settings.image.naturalWidth || 1;
const h = settings.image.naturalHeight || 1;
const sh = settings.mSize;
const sw = sh * w / h;
const sl = (1 - sw) * settings.mPosX;
const st = (1 - sh) * settings.mPosY;
const sr = sl + sw;
const sb = st + sh;
const pad = 0.01;
if (settings.mode === 3) {
// Strip
qr.add_blank(0, st - pad, size, sb + pad);
} else {
// Box
qr.add_blank(sl - pad, st - pad, sr + pad, sb + pad);
}
ctx.drawImage(settings.image, sl * size, st * size, sw * size, sh * size);
};
const draw_background = (qr, ctx, settings) => {
if (is_img_el(settings.background)) {
ctx.drawImage(settings.background, 0, 0, settings.size, settings.size);
} else if (settings.background) {
ctx.fillStyle = settings.background;
ctx.fillRect(settings.left, settings.top, settings.size, settings.size);
}
const mode = settings.mode;
if (mode === 1 || mode === 2) {
draw_background_label(qr, ctx, settings);
} else if (is_img_el(settings.image) && (mode === 3 || mode === 4)) {
draw_background_img(qr, ctx, settings);
}
};
const draw_modules_default = (qr, ctx, settings, left, top, width, row, col) => {
if (qr.is_dark(row, col)) {
ctx.r(left, top, width, width);
}
};
const draw_modules_rounded_dark = (ctx, l, t, r, b, rad, nw, ne, se, sw) => {
if (nw) {
ctx.m(l + rad, t);
} else {
ctx.m(l, t);
}
if (ne) {
ctx.l(r - rad, t).a(r, t, r, b, rad);
} else {
ctx.l(r, t);
}
if (se) {
ctx.l(r, b - rad).a(r, b, l, b, rad);
} else {
ctx.l(r, b);
}
if (sw) {
ctx.l(l + rad, b).a(l, b, l, t, rad);
} else {
ctx.l(l, b);
}
if (nw) {
ctx.l(l, t + rad).a(l, t, r, t, rad);
} else {
ctx.l(l, t);
}
};
const draw_modules_rounded_light = (ctx, l, t, r, b, rad, nw, ne, se, sw) => {
if (nw) {
ctx.m(l + rad, t).l(l, t).l(l, t + rad).a(l, t, l + rad, t, rad);
}
if (ne) {
ctx.m(r - rad, t).l(r, t).l(r, t + rad).a(r, t, r - rad, t, rad);
}
if (se) {
ctx.m(r - rad, b).l(r, b).l(r, b - rad).a(r, b, r - rad, b, rad);
}
if (sw) {
ctx.m(l + rad, b).l(l, b).l(l, b - rad).a(l, b, l + rad, b, rad);
}
};
const draw_modules_rounded = (qr, ctx, settings, left, top, width, row, col) => {
const right = left + width;
const bottom = top + width;
const rad = settings.radius * width;
const row_n = row - 1;
const row_s = row + 1;
const col_w = col - 1;
const col_e = col + 1;
const is_dark = qr.is_dark;
const d_center = is_dark(row, col);
const d_nw = is_dark(row_n, col_w);
const d_n = is_dark(row_n, col);
const d_ne = is_dark(row_n, col_e);
const d_e = is_dark(row, col_e);
const d_se = is_dark(row_s, col_e);
const d_s = is_dark(row_s, col);
const d_sw = is_dark(row_s, col_w);
const d_w = is_dark(row, col_w);
if (d_center) {
draw_modules_rounded_dark(ctx, left, top, right, bottom, rad, !d_n && !d_w, !d_n && !d_e, !d_s && !d_e, !d_s && !d_w);
} else {
draw_modules_rounded_light(ctx, left, top, right, bottom, rad, d_n && d_w && d_nw, d_n && d_e && d_ne, d_s && d_e && d_se, d_s && d_w && d_sw);
}
};
const draw_modules = (qr, ctx, settings) => {
const module_count = qr.module_count;
const module_size = settings.size / module_count;
let fn = draw_modules_default;
if (settings.radius > 0 && settings.radius <= 0.5) {
fn = draw_modules_rounded;
}
const draw_ctx = {
m(x, y) {ctx.moveTo(x, y); return draw_ctx;},
l(x, y) {ctx.lineTo(x, y); return draw_ctx;},
a(...args) {ctx.arcTo(...args); return draw_ctx;},
r(...args) {ctx.rect(...args); return draw_ctx;}
};
ctx.beginPath();
for (let row = 0; row < module_count; row += 1) {
for (let col = 0; col < module_count; col += 1) {
const l = settings.left + col * module_size;
const t = settings.top + row * module_size;
const w = module_size;
fn(qr, draw_ctx, settings, l, t, w, row, col);
}
}
if (is_img_el(settings.fill)) {
ctx.strokeStyle = 'rgba(0,0,0,0.5)';
ctx.lineWidth = 2;
ctx.stroke();
const prev = ctx.globalCompositeOperation;
ctx.globalCompositeOperation = 'destination-out';
ctx.fill();
ctx.globalCompositeOperation = prev;
ctx.clip();
ctx.drawImage(settings.fill, 0, 0, settings.size, settings.size);
ctx.restore();
} else {
ctx.fillStyle = settings.fill;
ctx.fill();
}
};
// Draws QR code to the given `canvas` and returns it.
const draw_on_canvas = (canvas, settings) => {
const qr = create_min_qrcode(settings.text, settings.ecLevel, settings.minVersion, settings.maxVersion, settings.quiet);
if (!qr) {
return null;
}
const $canvas = JQ(canvas).data('qrcode', qr);
const ctx = $canvas[0].getContext('2d');
draw_background(qr, ctx, settings);
draw_modules(qr, ctx, settings);
return $canvas;
};
// Returns a `canvas` element representing the QR code for the given settings.
const create_canvas = settings => {
const $canvas = JQ('<canvas/>').attr('width', settings.size).attr('height', settings.size);
return draw_on_canvas($canvas, settings);
};
// Returns an `image` element representing the QR code for the given settings.
const create_img = settings => {
return JQ('<img/>').attr('src', create_canvas(settings)[0].toDataURL('image/png'));
};
// Returns a `div` element representing the QR code for the given settings.
const create_div = settings => {
const qr = create_min_qrcode(settings.text, settings.ecLevel, settings.minVersion, settings.maxVersion, settings.quiet);
if (!qr) {
return null;
}
// some shortcuts to improve compression
const settings_size = settings.size;
const settings_bgColor = settings.background;
const math_floor = Math.floor;
const module_count = qr.module_count;
const module_size = math_floor(settings_size / module_count);
const offset = math_floor(0.5 * (settings_size - module_size * module_count));
const container_css = {
position: 'relative',
left: 0,
top: 0,
padding: 0,
margin: 0,
width: settings_size,
height: settings_size
};
const dark_css = {
position: 'absolute',
padding: 0,
margin: 0,
width: module_size,
height: module_size,
'background-color': settings.fill
};
const $div = JQ('<div/>').data('qrcode', qr).css(container_css);
if (settings_bgColor) {
$div.css('background-color', settings_bgColor);
}
for (let row = 0; row < module_count; row += 1) {
for (let col = 0; col < module_count; col += 1) {
if (qr.is_dark(row, col)) {
JQ('<div/>')
.css(dark_css)
.css({
left: offset + col * module_size,
top: offset + row * module_size
})
.appendTo($div);
}
}
}
return $div;
};
const create_html = settings => {
if (settings.render === 'canvas') {
return create_canvas(settings);
} else if (settings.render === 'image') {
return create_img(settings);
}
return create_div(settings);
};
const DEFAULTS = {
// render method: `'canvas'`, `'image'` or `'div'`
render: 'canvas',
// version range somewhere in 1 .. 40
minVersion: 1,
maxVersion: 40,
// error correction level: `'L'`, `'M'`, `'Q'` or `'H'`
ecLevel: 'L',
// offset in pixel if drawn onto existing canvas
left: 0,
top: 0,
// size in pixel
size: 200,
// code color or image element
fill: '#000',
// background color or image element, `null` for transparent background
background: '#fff',
// content
text: 'no text',
// corner radius relative to module width: 0.0 .. 0.5
radius: 0,
// quiet zone in modules
quiet: 0,
// modes
// 0: normal
// 1: label strip
// 2: label box
// 3: image strip
// 4: image box
mode: 0,
mSize: 0.1,
mPosX: 0.5,
mPosY: 0.5,
label: 'no label',
fontname: 'sans',
fontcolor: '#000',
image: null
};
JQ.fn.qrcode = module.exports = function main(options) {
const settings = JQ.extend({}, DEFAULTS, options);
return this.each((idx, el) => {
if (el.nodeName.toLowerCase() === 'canvas') {
draw_on_canvas(el, settings);
} else {
JQ(el).append(create_html(settings));
}
});
};

@ -1,469 +0,0 @@
(function ($) {
'use strict';
// Wrapper for the original QR code generator.
var QRCode = function (text, level, version, quiet) {
// `qrcode` is the single public function that will be defined by the `QR Code Generator`
// at the end of the file.
var qr = qrcode(version, level);
qr.addData(text);
qr.make();
quiet = quiet || 0;
var qrModuleCount = qr.getModuleCount(),
quietModuleCount = qr.getModuleCount() + 2*quiet,
isDark = function (row, col) {
row -= quiet;
col -= quiet;
if (row < 0 || row >= qrModuleCount || col < 0 || col >= qrModuleCount) {
return false;
}
return qr.isDark(row, col);
},
addBlank = function (l, t, r, b) {
var prevIsDark = this.isDark,
moduleSize = 1 / quietModuleCount;
this.isDark = function (row, col) {
var ml = col * moduleSize,
mt = row * moduleSize,
mr = ml + moduleSize,
mb = mt + moduleSize;
return prevIsDark(row, col) && (l > mr || ml > r || t > mb || mt > b);
};
};
this.text = text;
this.level = level;
this.version = version;
this.moduleCount = quietModuleCount;
this.isDark = isDark;
this.addBlank = addBlank;
},
// Check if canvas is available in the browser (as Modernizr does)
canvasAvailable = (function () {
var elem = document.createElement('canvas');
return !!(elem.getContext && elem.getContext('2d'));
}()),
arcToAvailable = Object.prototype.toString.call(window.opera) !== '[object Opera]',
// Returns a minimal QR code for the given text starting with version `minVersion`.
// Returns `null` if `text` is too long to be encoded in `maxVersion`.
createQRCode = function (text, level, minVersion, maxVersion, quiet) {
minVersion = Math.max(1, minVersion || 1);
maxVersion = Math.min(40, maxVersion || 40);
for (var version = minVersion; version <= maxVersion; version += 1) {
try {
return new QRCode(text, level, version, quiet);
} catch (err) {}
}
},
drawBackgroundLabel = function (qr, context, settings) {
var size = settings.size,
font = "bold " + (settings.mSize * size) + "px " + settings.fontname,
ctx = $('<canvas/>')[0].getContext("2d");
ctx.font = font;
var w = ctx.measureText(settings.label).width,
sh = settings.mSize,
sw = w / size,
sl = (1 - sw) * settings.mPosX,
st = (1 - sh) * settings.mPosY,
sr = sl + sw,
sb = st + sh,
pad = 0.01;
if (settings.mode === 1) {
// Strip
qr.addBlank(0, st - pad, size, sb + pad);
} else {
// Box
qr.addBlank(sl - pad, st - pad, sr + pad, sb + pad);
}
context.fillStyle = settings.fontcolor;
context.font = font;
context.fillText(settings.label, sl*size, st*size + 0.75 * settings.mSize * size);
},
drawBackgroundImage = function (qr, context, settings) {
var size = settings.size,
w = settings.image.naturalWidth || 1,
h = settings.image.naturalHeight || 1,
sh = settings.mSize,
sw = sh * w / h,
sl = (1 - sw) * settings.mPosX,
st = (1 - sh) * settings.mPosY,
sr = sl + sw,
sb = st + sh,
pad = 0.01;
if (settings.mode === 3) {
// Strip
qr.addBlank(0, st - pad, size, sb + pad);
} else {
// Box
qr.addBlank(sl - pad, st - pad, sr + pad, sb + pad);
}
context.drawImage(settings.image, sl*size, st*size, sw*size, sh*size);
},
drawBackground = function (qr, context, settings) {
if ($(settings.background).is('img')) {
context.drawImage(settings.background, 0, 0, settings.size, settings.size);
} else if (settings.background) {
context.fillStyle = settings.background;
context.fillRect(settings.left, settings.top, settings.size, settings.size);
}
var mode = settings.mode;
if (mode === 1 || mode === 2) {
drawBackgroundLabel(qr, context, settings);
} else if (mode === 3 || mode === 4) {
drawBackgroundImage(qr, context, settings);
}
},
drawModuleDefault = function (qr, context, settings, left, top, width, row, col) {
if (qr.isDark(row, col)) {
context.rect(left, top, width, width);
}
},
drawModuleRoundedDark = function (ctx, l, t, r, b, rad, nw, ne, se, sw) {
if (nw) {
ctx.moveTo(l + rad, t);
} else {
ctx.moveTo(l, t);
}
if (ne) {
ctx.lineTo(r - rad, t);
ctx.arcTo(r, t, r, b, rad);
} else {
ctx.lineTo(r, t);
}
if (se) {
ctx.lineTo(r, b - rad);
ctx.arcTo(r, b, l, b, rad);
} else {
ctx.lineTo(r, b);
}
if (sw) {
ctx.lineTo(l + rad, b);
ctx.arcTo(l, b, l, t, rad);
} else {
ctx.lineTo(l, b);
}
if (nw) {
ctx.lineTo(l, t + rad);
ctx.arcTo(l, t, r, t, rad);
} else {
ctx.lineTo(l, t);
}
},
drawModuleRoundendLight = function (ctx, l, t, r, b, rad, nw, ne, se, sw) {
if (nw) {
ctx.moveTo(l + rad, t);
ctx.lineTo(l, t);
ctx.lineTo(l, t + rad);
ctx.arcTo(l, t, l + rad, t, rad);
}
if (ne) {
ctx.moveTo(r - rad, t);
ctx.lineTo(r, t);
ctx.lineTo(r, t + rad);
ctx.arcTo(r, t, r - rad, t, rad);
}
if (se) {
ctx.moveTo(r - rad, b);
ctx.lineTo(r, b);
ctx.lineTo(r, b - rad);
ctx.arcTo(r, b, r - rad, b, rad);
}
if (sw) {
ctx.moveTo(l + rad, b);
ctx.lineTo(l, b);
ctx.lineTo(l, b - rad);
ctx.arcTo(l, b, l + rad, b, rad);
}
},
drawModuleRounded = function (qr, context, settings, left, top, width, row, col) {
var isDark = qr.isDark,
right = left + width,
bottom = top + width,
radius = settings.radius * width,
rowT = row - 1,
rowB = row + 1,
colL = col - 1,
colR = col + 1,
center = isDark(row, col),
northwest = isDark(rowT, colL),
north = isDark(rowT, col),
northeast = isDark(rowT, colR),
east = isDark(row, colR),
southeast = isDark(rowB, colR),
south = isDark(rowB, col),
southwest = isDark(rowB, colL),
west = isDark(row, colL);
if (center) {
drawModuleRoundedDark(context, left, top, right, bottom, radius, !north && !west, !north && !east, !south && !east, !south && !west);
} else {
drawModuleRoundendLight(context, left, top, right, bottom, radius, north && west && northwest, north && east && northeast, south && east && southeast, south && west && southwest);
}
},
drawModules = function (qr, context, settings) {
var moduleCount = qr.moduleCount,
moduleSize = settings.size / moduleCount,
fn = drawModuleDefault,
row, col;
if (arcToAvailable && settings.radius > 0 && settings.radius <= 0.5) {
fn = drawModuleRounded;
}
context.beginPath();
for (row = 0; row < moduleCount; row += 1) {
for (col = 0; col < moduleCount; col += 1) {
var l = settings.left + col * moduleSize,
t = settings.top + row * moduleSize,
w = moduleSize;
fn(qr, context, settings, l, t, w, row, col);
}
}
if ($(settings.fill).is('img')) {
context.strokeStyle = 'rgba(0,0,0,0.5)';
context.lineWidth = 2;
context.stroke();
var prev = context.globalCompositeOperation;
context.globalCompositeOperation = "destination-out";
context.fill();
context.globalCompositeOperation = prev;
context.clip();
context.drawImage(settings.fill, 0, 0, settings.size, settings.size);
context.restore();
} else {
context.fillStyle = settings.fill;
context.fill();
}
},
// Draws QR code to the given `canvas` and returns it.
drawOnCanvas = function (canvas, settings) {
var qr = createQRCode(settings.text, settings.ecLevel, settings.minVersion, settings.maxVersion, settings.quiet);
if (!qr) {
return null;
}
var $canvas = $(canvas).data('qrcode', qr),
context = $canvas[0].getContext('2d');
drawBackground(qr, context, settings);
drawModules(qr, context, settings);
return $canvas;
},
// Returns a `canvas` element representing the QR code for the given settings.
createCanvas = function (settings) {
var $canvas = $('<canvas/>').attr('width', settings.size).attr('height', settings.size);
return drawOnCanvas($canvas, settings);
},
// Returns an `image` element representing the QR code for the given settings.
createImage = function (settings) {
return $('<img/>').attr('src', createCanvas(settings)[0].toDataURL('image/png'));
},
// Returns a `div` element representing the QR code for the given settings.
createDiv = function (settings) {
var qr = createQRCode(settings.text, settings.ecLevel, settings.minVersion, settings.maxVersion, settings.quiet);
if (!qr) {
return null;
}
// some shortcuts to improve compression
var settings_size = settings.size,
settings_bgColor = settings.background,
math_floor = Math.floor,
moduleCount = qr.moduleCount,
moduleSize = math_floor(settings_size / moduleCount),
offset = math_floor(0.5 * (settings_size - moduleSize * moduleCount)),
row, col,
containerCSS = {
position: 'relative',
left: 0,
top: 0,
padding: 0,
margin: 0,
width: settings_size,
height: settings_size
},
darkCSS = {
position: 'absolute',
padding: 0,
margin: 0,
width: moduleSize,
height: moduleSize,
'background-color': settings.fill
},
$div = $('<div/>').data('qrcode', qr).css(containerCSS);
if (settings_bgColor) {
$div.css('background-color', settings_bgColor);
}
for (row = 0; row < moduleCount; row += 1) {
for (col = 0; col < moduleCount; col += 1) {
if (qr.isDark(row, col)) {
$('<div/>')
.css(darkCSS)
.css({
left: offset + col * moduleSize,
top: offset + row * moduleSize
})
.appendTo($div);
}
}
}
return $div;
},
createHTML = function (settings) {
if (canvasAvailable && settings.render === 'canvas') {
return createCanvas(settings);
} else if (canvasAvailable && settings.render === 'image') {
return createImage(settings);
}
return createDiv(settings);
},
// Plugin
// ======
// Default settings
// ----------------
defaults = {
// render method: `'canvas'`, `'image'` or `'div'`
render: 'canvas',
// version range somewhere in 1 .. 40
minVersion: 1,
maxVersion: 40,
// error correction level: `'L'`, `'M'`, `'Q'` or `'H'`
ecLevel: 'L',
// offset in pixel if drawn onto existing canvas
left: 0,
top: 0,
// size in pixel
size: 200,
// code color or image element
fill: '#000',
// background color or image element, `null` for transparent background
background: null,
// content
text: 'no text',
// corner radius relative to module width: 0.0 .. 0.5
radius: 0,
// quiet zone in modules
quiet: 0,
// modes
// 0: normal
// 1: label strip
// 2: label box
// 3: image strip
// 4: image box
mode: 0,
mSize: 0.1,
mPosX: 0.5,
mPosY: 0.5,
label: 'no label',
fontname: 'sans',
fontcolor: '#000',
image: null
};
// Register the plugin
// -------------------
$.fn.qrcode = function(options) {
var settings = $.extend({}, defaults, options);
return this.each(function () {
if (this.nodeName.toLowerCase() === 'canvas') {
drawOnCanvas(this, settings);
} else {
$(this).append(createHTML(settings));
}
});
};
// jQuery.qrcode plug in code ends here
// QR Code Generator
// =================
// @include "qrcode.js"
}(jQuery));

File diff suppressed because it is too large Load Diff
Loading…
Cancel
Save