Reputation: 5250
I am using 2 canvas elements. I am using one element as a main canvas element which has all the elements. I am generating a barcode in a separate canvas and would like to add it to the main canvas. Trying for a long time. Adding an example here fiddle
$(document).ready(function() {
JsBarcode('#barcode', "1234", {
width: 4,
height: 20//displayValue: false
});
var bc = document.getElementById("barcode");
var canvasx = bc.getContext("2d");
var img1 = new Image();
img1.src = bc.toDataURL("image/png");
var c = document.getElementById("labelDesigner");
var canvas = bc.getContext("2d");
c.drawImage(img1);
});
I am using facric.js and JsBarcode. Thanks for the help in advance. If there is any other better way kindly suggest
Upvotes: 0
Views: 298
Reputation: 15604
you can use fabric.Image.fromURL and pass the barcode canvas data as url.
DEMO
$(document).ready(function() {
JsBarcode('#barcode', "1234", {
width: 4,
height: 20 //displayValue: false
});
var canvas = new fabric.Canvas("labelDesigner");
var bc = document.getElementById("barcode");
fabric.Image.fromURL(bc.toDataURL(),function(img){
img.set({
left: 0,
top: 0
})
canvas.add(img);
})
});
canvas[id^=c], div[id=output] {
border: 1px solid red;
}
canvas[id=buffer] {
border: 1px dotted green;
}
#output {
padding: 15px;
}
#output img {
border: 1px dotted blue;
}
<script src="https://rawgit.com/kangax/fabric.js/master/dist/fabric.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jsbarcode/3.9.0/JsBarcode.all.min.js"></script>
<canvas id="barcode"></canvas>
<canvas id="labelDesigner" width="410" height="200" style="border:1px solid #000000;margin-left:200px"></canvas>
Upvotes: 1
Reputation: 31846
The drawImage
-function can take another canvas as an argument, so you do not have to convert to an image inbetween. However, it always requires the x and y coordinates as the second and third parameters.
You had also swapped your c
and canvas
variables:
$(document).ready(function() {
JsBarcode('#barcode', "1234", {
width: 4,
height: 20//displayValue: false
});
var bc = document.getElementById("barcode");
var c = document.getElementById("labelDesigner");
var context = c.getContext("2d");
context.drawImage(bc, 0, 0);
});
Upvotes: 0