Skip to content

Commit

Permalink
optionally rendering barcode directly to a canvas instead of an image
Browse files Browse the repository at this point in the history
It is now possible to use either an image- or a canvas-object to render the barcode to
  • Loading branch information
schaumiii committed Dec 30, 2014
1 parent ffc6e24 commit 14f8e0c
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 9 deletions.
35 changes: 27 additions & 8 deletions JsBarcode.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,23 @@
options = merge(JsBarcode.defaults, options);

//Create the canvas where the barcode will be drawn on
var canvas = document.createElement('canvas');

// Check if the given image is already a canvas
var canvas = image;

// check if it is a jQuery selection
if (image instanceof jQuery) {
// get the DOM element of the selection
canvas = image.get(0);
// check if DOM element is a canvas, otherwise it will be probably an image so create a canvas
if (!(canvas instanceof HTMLCanvasElement)) {
canvas = document.createElement('canvas');
}
} else if (!(image instanceof HTMLCanvasElement)) {
// there is no jQuery selection so just check if DOM element is a canvas, otherwise it will be probably
// an image so create a canvas
canvas = document.createElement('canvas');
}

//Abort if the browser does not support HTML5canvas
if (!canvas.getContext) {
return image;
Expand Down Expand Up @@ -88,12 +103,16 @@

//Grab the dataUri from the canvas
uri = canvas.toDataURL('image/png');

//Put the data uri into the image
if (image.attr) { //If element has attr function (jQuery element)
return image.attr("src", uri);
}
else { //DOM element

// check if given image is a jQuery selection
if (image instanceof jQuery) {
// check if the given image was a canvas, if not set the source attribute of the image
if (!(image.get(0) instanceof HTMLCanvasElement)) {
//Put the data uri into the image
return image.attr("src", uri);
}
} else if (!(image instanceof HTMLCanvasElement)) {
// There is no jQuery selection so just check if the given image was a canvas, if not set the source attr
image.setAttribute("src", uri);
}

Expand Down
6 changes: 5 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -56,10 +56,14 @@ JsBarcode(object, string, options);
Examples
----

####First we need an image
####First we need an image (or an canvas - it works both ways!)
````html
<img id="barcode">
````
or
````html
<canvas id="barcode"></canvas
````

#### This code:
````javascript
Expand Down

0 comments on commit 14f8e0c

Please sign in to comment.