I can load an image into a canvas element and resize it, but I'm having trouble grabbing the resized image:
var logo = $(".logo"),
loader = $(".load"),
canvas = $(".holder"),
ctx = canvas[0].getContext("2d");
function displayPreview(file) {
var reader = new FileReader();
reader.onload = function(e) {
var img = new Image();
img.src = e.target.result;
img.onload = function() {
// x, y, width, height
ctx.drawImage(img, 0, 0, 128, 128);
var dataURL = canvas[0].toDataURL("image/png");
var logo = $(".logo");
var imgUrl = dataURL;
var imgz = $("<img>");
imgz.attr("src", imgUrl);
logo.html("");
logo.append(imgz);
};
};
reader.readAsDataURL(file);
}
into the download package function for jszip.
// Download Zip
$(".download").on("click", function(imgUrl) {
var zip = new JSZip();
zip.file("logo.png", imgUrl);
var content = zip.generate({type:"blob"});
// see FileSaver.js
saveAs(content, "test.zip");
});
Snippet:
var logo = $(".logo"),
loader = $(".load"),
canvas = $(".holder"),
ctx = canvas[0].getContext("2d");
function displayPreview(file) {
var reader = new FileReader();
reader.onload = function(e) {
var img = new Image();
img.src = e.target.result;
img.onload = function() {
// x, y, width, height
ctx.drawImage(img, 0, 0, 128, 128);
var dataURL = canvas[0].toDataURL("image/png");
var logo = $(".logo");
var imgUrl = dataURL;
var imgz = $("<img>");
imgz.attr("src", imgUrl);
logo.html("");
logo.append(imgz);
};
};
reader.readAsDataURL(file);
}
$(document).ready(function() {
loader.on("change", function(evt) {
var file = evt.target.files[0];
displayPreview(file);
var reader = new FileReader();
reader.onload = function(e) {
// Download Zip
$(".download").on("click", function(imgUrl) {
var zip = new JSZip();
zip.file("logo.png", imgUrl);
var content = zip.generate({type:"blob"});
// see FileSaver.js
saveAs(content, "test.zip");
});
return false;
};
reader.readAsArrayBuffer(file);
});
// Trigger Load Image
$(".trigload").click(function() {
$("input").trigger("click");
});
});
#import url("http://necolas.github.io/normalize.css/3.0.1/normalize.css");
.hide {
display: none;
}
.logo {
text-align: center;
}
.fill {
width: 100%;
}
.fr {
float: right;
}
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<script type="text/javascript" src="http://stuk.github.io/jszip/dist/jszip.min.js"></script>
<script type="text/javascript" src="http://stuk.github.io/jszip-utils/dist/jszip-utils.js"></script>
<script type="text/javascript" src="http://stuk.github.io/jszip/vendor/FileSaver.js"></script>
<input type="file" class="hide load">
<a class="trigload" href="javascript:void(0)">Load Image</a>
<a class="download fr" href="javascript:void(0)">Download</a>
<div class="logo"></div>
<div class="fill" align="center">
<canvas class="holder" width="128" height="128"></canvas>
</div>
In order to get JSZip to correctly save your dataURL to valid png file, it seems you need to add an object containing {base64: true}as third argument of the zip.file() method, and to remove the data:image/png;base64, from the dataURL.
Also, you were assigning the click event to the imgUrl variable. You may want to store it in a global variable, or check the $('.logo>img')[0].src or call once again canvas[0].toDataURL().
var logo = $(".logo"),
loader = $(".load"),
canvas = $(".holder"),
ctx = canvas[0].getContext("2d");
function displayPreview(file) {
var reader = new FileReader();
reader.onload = function(e) {
var img = new Image();
img.src = e.target.result;
img.onload = function() {
// x, y, width, height
ctx.drawImage(img, 0, 0, 128, 128);
var dataURL = canvas[0].toDataURL("image/png");
var logo = $(".logo");
var imgUrl = dataURL;
var imgz = $("<img>");
imgz.attr("src", imgUrl);
logo.html("");
logo.append(imgz);
};
};
reader.readAsDataURL(file);
}
$(document).ready(function() {
loader.on("change", function(evt) {
var file = evt.target.files[0];
displayPreview(file);
var reader = new FileReader();
reader.onload = function(e) {
// Download Zip
$(".download").on("click", function() {
var imgUrl = canvas[0].toDataURL();
var zip = new JSZip();
zip.file("logo.png", imgUrl.split('base64,')[1],{base64: true});
var content = zip.generate({type:"blob"});
// see FileSaver.js
saveAs(content, "test.zip");
});
return false;
};
reader.readAsArrayBuffer(file);
});
// Trigger Load Image
$(".trigload").click(function() {
$("input").trigger("click");
});
});
#import url("http://necolas.github.io/normalize.css/3.0.1/normalize.css");
.hide {
display: none;
}
.logo {
text-align: center;
}
.fill {
width: 100%;
}
.fr {
float: right;
}
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<script type="text/javascript" src="http://stuk.github.io/jszip/dist/jszip.min.js"></script>
<script type="text/javascript" src="http://stuk.github.io/jszip-utils/dist/jszip-utils.js"></script>
<script type="text/javascript" src="http://stuk.github.io/jszip/vendor/FileSaver.js"></script>
<input type="file" class="hide load">
<a class="trigload" href="javascript:void(0)">Load Image</a>
<a class="download fr" href="javascript:void(0)">Download</a>
<div class="logo"></div>
<div class="fill" align="center">
<canvas class="holder" width="128" height="128"></canvas>
</div>
2022 Edit
JSZip now accepts Blobs as input directly, so it's better to convert your canvas to a Blob and pass this directly to JSZip. (As a fiddle because StackSnippets don't allow-downloads).
Related
I tried to load images into several canvas elements, but only the last image was loaded from the list of files. I need different images in different canvas elements, each in its own. Thanks for help.
HTML
<input type='file' id='imgfile' multiple />
The canvas element will be created by jQuery.
JavaScript
function loadImage(picture) {
var canvas = document.querySelectorAll('canvas');
var input, fr, file, img;
input = document.getElementById('imgfile');
$.each(canvas, function(i, v) {
file = input.files[i];
fr = new FileReader();
fr.onload = function createImage() {
img = new Image();
img.onload = function imageLoaded() {
var ctx = canvas[i].getContext("2d");
ctx.drawImage(img, 0, 0, 50, 50);
}
img.src = fr.result;
}
fr.readAsDataURL(file);
});
}
$("input").change(function() {
var picture = this.files;
var leng = picture.length;
for (var i = 0; i < picture.length; i++) {
$("input").after('<canvas width="50" height="50" style="border:1px solid red"></canvas>');
}
loadImage();
});
You need to declare variables inside iteratee function
function loadImage(picture) {
var canvas = document.querySelectorAll('canvas');
var input = document.getElementById('imgfile');
$.each( canvas, function( i, v) {
var file = input.files[i];
var fr = new FileReader(); // file reader per file
fr.onload = function createImage() {
var img = new Image(); // image per file
img.onload = function imageLoaded() {
var ctx = canvas[i].getContext("2d");
ctx.drawImage(img,0,0, 50, 50);
}
img.src = fr.result;
}
fr.readAsDataURL(file);
});
}
I have a FabricJS canvas (1.7.22) with a few buttons to add images and text. I also have a textarea which I can use to load the canvas JSON for copying and to load to the canvas for later editing.
I want to expedite the process by being able to save the canvas JSON as a file to my computer and be able to load the file onto the canvas later.
I feel like I have the essential functionality but how might I achieve the above for better usability?
$(function() {
var canvas = new fabric.Canvas('c', {
/* isDrawingMode: true */
});
$('#text').on('click', addtext);
function addtext() {
var text = new fabric.IText('Some Text!', {
left: 10,
top: 10
});
canvas.add(text);
}
// From Computer
document.getElementById('imgLoader').onchange = function handleImage(e) {
var reader = new FileReader();
reader.onload = function(event) {
console.log('fdsf');
var imgObj = new Image();
imgObj.src = event.target.result;
imgObj.onload = function() {
// start fabricJS stuff
var image = new fabric.Image(imgObj);
image.set({
left: 0,
top: 0,
angle: 20,
padding: 10,
cornersize: 10
});
//image.scale(getRandomNum(0.1, 0.25)).setCoords();
image.scale(0.2);
canvas.add(image);
// end fabricJS stuff
}
}
reader.readAsDataURL(e.target.files[0]);
}
// Add Web IMG
var myImg = 'https://i.imgur.com/q2oGjQ9.jpg';
$('#addImage').on('click', addImg);
function addImg() {
fabric.Image.fromURL(myImg, function(oImg) {
oImg.scale(0.2);
canvas.add(oImg);
});
}
// canvas2json
$("#canvas2json").click(function() {
var json = canvas.toJSON();
$("#myTextArea").text(JSON.stringify(json));
});
// load json2canvas
$("#loadJson2Canvas").click(function() {
canvas.loadFromJSON(
$("#myTextArea").val(),
canvas.renderAll.bind(canvas));
});
});
#myTextArea {
width: 90%;
height: 200px;
}
canvas {
border: 1px solid black
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.7.22/fabric.min.js"></script>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<button id="text">Add Text</button>
<input type="button" id="addImage" value="Add Web IMG">
<input type="file" id="imgLoader">
<br/><br/>
<canvas id='c' width=500 height=500></canvas>
<br/>
<button id='canvas2json'>2JSON</button>
<button id='loadJson2Canvas'>2CANVAS</button>
<br/><br/>
<textarea id='myTextArea' onfocus="this.select();" onmouseup="return false;"></textarea>
Download the json using createObjectURL and then upload from browser and read the file using readAsText , FileReader api . then load JSON to canvas.
DEMO
$(function() {
var canvas = new fabric.Canvas('c', {
/* isDrawingMode: true */
});
$('#text').on('click', addtext);
function addtext() {
var text = new fabric.IText('Some Text!', {
left: 10,
top: 10
});
canvas.add(text);
}
// From Computer
document.getElementById('imgLoader').onchange = function handleImage(e) {
var reader = new FileReader();
reader.onload = function(event) {
console.log('fdsf');
var imgObj = new Image();
imgObj.src = event.target.result;
imgObj.onload = function() {
// start fabricJS stuff
var image = new fabric.Image(imgObj);
image.set({
left: 0,
top: 0,
angle: 20,
padding: 10,
cornersize: 10
});
//image.scale(getRandomNum(0.1, 0.25)).setCoords();
image.scale(0.2);
canvas.add(image);
// end fabricJS stuff
}
}
reader.readAsDataURL(e.target.files[0]);
}
// Add Web IMG
var myImg = 'https://i.imgur.com/q2oGjQ9.jpg';
$('#addImage').on('click', addImg);
function addImg() {
fabric.Image.fromURL(myImg, function(oImg) {
oImg.scale(0.2);
canvas.add(oImg);
});
}
// canvas2json
$("#canvas2json").click(function() {
var json = canvas.toJSON();
$("#myTextArea").text(JSON.stringify(json));
var a = document.createElement("a");
var file = new Blob([JSON.stringify(json)], {
type: 'text/plain'
});
a.href = URL.createObjectURL(file);
a.download = 'json.txt';
a.click();
});
// load json2canvas
$("#loadJson2Canvas").click(function() {
canvas.loadFromJSON(
$("#myTextArea").val(),
canvas.renderAll.bind(canvas));
});
$('#jsonload').change(function(e) {
var file = e.target.files[0];
if(!file) return;
var reader = new FileReader();
reader.onload = function(f) {
var data = f.target.result;
canvas.loadFromJSON(
JSON.parse(data),
canvas.renderAll.bind(canvas));
};
reader.readAsText(file);
});
$(this).val(null);
return;
});
#myTextArea {
width: 90%;
height: 200px;
}
canvas {
border: 1px solid black
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.7.22/fabric.min.js"></script>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<button id="text">Add Text</button>
<input type="button" id="addImage" value="Add Web IMG"/><input type="file" id="imgLoader"/>
<br>upload json<input type="file" id="jsonload" />
<br/><br/>
<canvas id='c' width=500 height=500></canvas>
<br/>
<button id='canvas2json'>2JSON</button>
<button id='loadJson2Canvas'>2CANVAS</button>
<br/><br/>
<textarea id='myTextArea' onfocus="this.select();" onmouseup="return false;"></textarea>
Use localStorage to save data to your hard drive. For example
$("#canvas2json").click(function() {
localStorage.myFabricJSCanvas = JSON.stringify(canvas.toJSON());
$("#myTextArea").text('Saved');
});
$("#loadJson2Canvas").click(function() {
canvas.loadFromJSON(
JSON.parse(localStorage.myFabricJSCanvas),
canvas.renderAll.bind(canvas)
);
});
If you want to make it more flexible, such as with more load/save slots, then load/save from a container object such as myCanvases, assign to / get data from its values, and save the myCanvases object to localStorage instead.
I am working with canvas, right now I can save into DB and I can change the background image to one I choose of a image list.
My problem is when I tried to save the canvas with the background the saved image just show me the draw but doesn't the image background...can somebody help me with this?
Best Regards!
Here the code:
<script src="js/drawingboard.min.js"></script>
<script data-example="1">
var defaultBoard = new DrawingBoard.Board("default-board", {
background: "#ffff",
droppable: true,
webStorage: false,
enlargeYourContainer: true,
addToBoard: true,
stretchImg: false
});
defaultBoard.addControl("Download");
$(".drawing-form").on("submit", function(e) {
var img = defaultBoard.getImg();
var imgInput = (defaultBoard.blankCanvas == img) ? "" : img;
$(this).find("input[name=image]").val( imgInput );
defaultBoard.clearWebStorage();
});
$(function() {
$("#file-input").change(function(e) {
var file = e.target.files[0],
imageType = /image.*/;
if (!file.type.match(imageType))
return;
var reader = new FileReader();
reader.onload = fileOnload;
reader.readAsDataURL(file);
});
function fileOnload(e) {
var $img = $("<img>", { src: e.target.result });
var canvas = $("#default-board")[0];
var context = canvas.getContext("2d");
$img.load(function() {
context.drawImage(this, 0, 0);
});
}
});
</script>
<script src="js/yepnope.js"></script>
<script>
var iHasRangeInput = function() {
var inputElem = document.createElement("input"),
smile = ":)",
docElement = document.documentElement,
inputElemType = "range",
available;
inputElem.setAttribute("type", inputElemType);
available = inputElem.type !== "text";
inputElem.value = smile;
inputElem.style.cssText = "position:absolute;visibility:hidden;";
if ( /^range$/.test(inputElemType) && inputElem.style.WebkitAppearance !== undefined ) {
docElement.appendChild(inputElem);
defaultView = document.defaultView;
available = defaultView.getComputedStyle &&
defaultView.getComputedStyle(inputElem, null).WebkitAppearance !== "textfield" &&
(inputElem.offsetHeight !== 0);
docElement.removeChild(inputElem);
}
return !!available;
};
yepnope({
test : iHasRangeInput(),
nope : ["css/fd-slider.min.css", "js/fd-slider.min.js"],
callback: function(id, testResult) {
if("fdSlider" in window && typeof (fdSlider.onDomReady) != "undefined") {
try { fdSlider.onDomReady(); } catch(err) {}
}
}
});
// with this code I can change the background
$(document).ready(function () {
$("#cambiocanvas > input").click(function () {
var img = $(this).attr("src");
$(".drawing-board-canvas").css("background", "url(" + img + ")");
});
});
</script>
Here the form with the images:
<div class="tab-pane" id="derm">
<div class="row-fluid sortable">
<div class="box span3">
<section id="cambiocanvas">
<input id="yellowcanvas" class="canvasborder" type="image" src="http://2.imimg.com/data2/MB/BH/MY-651900/23-250x250.jpg">
<input id="bluecanvas" class="canvasborder" type="image" src="http://jsfiddle.net/img/logo.png">
<input id="greencanvas" class="canvasborder" type="image" src="https://www.gravatar.com/avatar/86364f16634c5ecbb25bea33dd9819da?s=128&d=identicon&r=PG&f=1">
</section>
</div>
<div class="box span9">
<div class="box-header well" data-original-title>
<h2><i class="icon-tasks"></i> </h2>
<div class="box-icon">
<i class="icon-chevron-up"></i>
<i class="icon-remove"></i>
</div>
</div>
<div class="box-content">
<div id="container">
<div class="example" data-example="1">
<div class="board" id="default-board"></div>
</div>
<form class="drawing-form" method="post" name="diagram" id="diagram" enctype="multipart/form-data">
<div id="board"></div>
<input type="hidden" name="image" value="">
<input type="hidden" name="id_user" value="<?php echo $id" />
<br><hr>
<button class="btn btn-info" id="btnUpload">Save</button>
</form>
<div id="ldiag" style="display:none;"><img src="images/loading4.gif" /></div>
<div class="progress1"></div>
<div id="diaga"></div>
</div>
</div>
</div>
CODE EDITED
Here the code:
<script src="js/drawingboard.min.js"></script>
<script data-example="1">
var defaultBoard = new DrawingBoard.Board("default-board", {
background: "#ffff",
droppable: true,
webStorage: false,
enlargeYourContainer: true,
addToBoard: true,
stretchImg: false
});
defaultBoard.addControl("Download");
$(".drawing-form").on("submit", function(e) {
var img = defaultBoard.getImg();
var imgInput = (defaultBoard.blankCanvas == img) ? "" : img;
$(this).find("input[name=image]").val( imgInput );
defaultBoard.clearWebStorage();
});
$(function() {
$("#file-input").change(function(e) {
var file = e.target.files[0],
imageType = /image.*/;
if (!file.type.match(imageType))
return;
var reader = new FileReader();
reader.onload = fileOnload;
reader.readAsDataURL(file);
});
function fileOnload(e) {
var canvas = $("#default-board")[0];
var context = canvas.getContext("2d");
var background = new Image;
background.src = canvas.style.background.replace(/url\(/|\)/gi,"").trim();
background.onload = function(){
var $img = $("<img>", { src: e.target.result });
$img.load(function() {
context.drawImage(backgroundImage, 0, 0, canvas.width, canvas.height);
context.drawImage(this, 0, 0);
});
}
}
});
The canvas element's background (image) is not part of the canvas content and thus not saved.
Solution if you can not redraw the canvas
If you want the background just render it onto the canvas before you save using the composite operation "destination-over" it will only add pixels where the canvas is transparent or semi transparent and you would see the Elements background.
ctx.globalCompositeOperation = "destination-over";
ctx.drawImage(backgroundImage,0,0);
ctx.globalCompositeOperation = "source-over"; // restore default
To load the canvas CSS background image
var background = new Image;
background.src = canvas.style.background.replace(/url\(/|\)/gi,"").trim();
// wait till it has loaded.
You may have to stretch the image
ctx.drawImage(background,0,0,ctx.canvas.width,ctx.canvas.height);
Alternative solution uses a offscreen canvas and draws background first then the original canvas.
// ensure that the image has loaded before running this code.
// canvas is the original canvas that you want to add the background to
// ctx is the origin canvas context
var can2 = document.createElement("canvas");
can2.width = canvas.width;
can2.height = canvas.height;
var ctx2 = can2.getContext("2d");
ctx2.drawImage(background,0,0,ctx.canvas.width,ctx.canvas.height);
ctx2.drawImage(canvas,0,0);
// put the new result back in the original canvas so you can save it without changing code.
ctx.clearRect(0,0,ctx.canvas.width,ctx.canvas.height);
ctx.drawImage(can2,0,0);
OR to provide a copy and paste solution
function fileOnload(e) {
var canvas = $("#default-board")[0];
var context = canvas.getContext("2d");
var background = new Image;
background.src = canvas.style.background.replace(/url\(|\)/gi,"").trim();
background.onload = function(){
var $img = $("<img>", { src: e.target.result });
$img.load(function() {
context.drawImage(backgroundImage, 0, 0, canvas.width, canvas.height);
context.drawImage(this, 0, 0);
});
}
});
You almost done. Try change this code:
$(document).ready(function () {
$("#cambiocanvas > input").click(function () {
var img = $(this).attr("src");
$("#default-board").css("background", "url(" + img + ")");
});
});
To this one:
$(".canvasborder").click(function(){
var src = $(this).attr("src");
defaultBoard.setImg(src);
});
Like this:
var defaultBoard = new DrawingBoard.Board("default-board", {
background: "#fff",
droppable: true,
webStorage: false,
enlargeYourContainer: true,
addToBoard: true,
stretchImg: true
});
defaultBoard.addControl("Download");
$(".canvasborder").click(function(){
var src = $(this).attr("src");
defaultBoard.setImg(src);
});
$(".drawing-form").on("submit", function(e) {
var img = defaultBoard.getImg();
var imgInput = (defaultBoard.blankCanvas == img) ? "" : img;
$(this).find("input[name=image]").val( imgInput );
defaultBoard.clearWebStorage();
});
$(function() {
$("#file-input").change(function(e) {
var file = e.target.files[0],
imageType = /image.*/;
if (!file.type.match(imageType))
return;
var reader = new FileReader();
reader.onload = fileOnload;
reader.readAsDataURL(file);
});
function fileOnload(e) {
var canvas = $("#default-board")[0];
var context = canvas.getContext("2d");
var background = new Image;
background.src = canvas.style.background.replace(/url\(|\)/gi,"").trim();
background.onload = function(){
var $img = $("<img>", { src: e.target.result });
$img.load(function() {
context.drawImage(backgroundImage, 0, 0, canvas.width, canvas.height);
context.drawImage(this, 0, 0);
});
}
}
});
And will be work with any image you put in the select list, remember it has to be accompanied by an Access-Control-Allow-Origin header allowing the origin of your page (potentially via the * wildcard).
I am using HTML5. Right now I am convert canvas into image by toDataURL. But I want to this canvas convert into different size. For example, My canvas size is 450px*450px then it should convert into 1000px*1000px.
var canvas = new fabric.Canvas('canvas');
document.getElementById('file').addEventListener("change", function (e) {
var file = e.target.files[0];
var reader = new FileReader();
reader.onload = function (f) {
var data = f.target.result;
fabric.Image.fromURL(data, function (img) {
var oImg = img.set({left: 50, top: 100,width:100, height:100, angle: 00}).scale(0.9);
canvas.add(oImg).renderAll();
var a = canvas.setActiveObject(oImg);
var dataURL = canvas.toDataURL({format: 'png', quality: 0.8, width:1000, height:10000});
console.log("aaaaaaaaaaa" + dataURL);
// console.log("Canvas Image " + dataURL);
// document.getElementById('txt').href = dataURL;
});
};
reader.readAsDataURL(file);
});
document.querySelector('#txt').onclick = function (e) {
e.preventDefault();
canvas.deactivateAll().renderAll();
document.querySelector('#preview').src = canvas.toDataURL();
}
canvas {
border: 1px solid black;
}
<script src="https://rawgit.com/kangax/fabric.js/master/dist/fabric.min.js"></script>
<input type="file" id="file">
<canvas id="canvas" width="400" height="400"></canvas>
Click Me!!
<br />
<img id="preview" />
I tried canvas.toDataUrl({format: 'png', quality: 0.8, width:1000,
height:1000}) But it is not works.
DEMO JSFIDDLE.
https://jsfiddle.net/varunPes/8gt6d7op/13/
expected Result:
Just add width:1000, height:1000 to var oImg = img.set({left: 50, top: 100, angle: 00}).scale(0.9);
Full Code:
var canvas = new fabric.Canvas('canvas');
document.getElementById('file').addEventListener("change", function (e) {
var file = e.target.files[0];
var reader = new FileReader();
reader.onload = function (f) {
var data = f.target.result;
fabric.Image.fromURL(data, function (img) {
var oImg = img.set({left: 0, top: 0, angle: 00}).scale(0.9);
canvas.add(oImg).renderAll();
var a = canvas.setActiveObject(oImg);
var dataURL = canvas.toDataURL({format: 'png', quality: 0.8});
});
};
reader.readAsDataURL(file);
});
document.querySelector('#txt').onclick = function (e) {
e.preventDefault();
canvas.deactivateAll().renderAll();
increaseImg(canvas.toDataURL(), function(dataURL) {
document.querySelector('#preview').src = dataURL;
});
}
function increaseImg(src, callback) {
var n_canvas = $('<canvas width="1800" height="2000" />')[0],
n_ctx = n_canvas.getContext('2d'),
n_img = new Image();
n_img.onload = function() {
n_ctx.drawImage(n_img, 0, 0, n_canvas.width, n_canvas.height);
callback(n_canvas.toDataURL());
}
n_img.src = src;
}
canvas{
border: 1px solid black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://rawgit.com/kangax/fabric.js/master/dist/fabric.min.js"></script>
<input type="file" id="file"><br />
<canvas id="canvas" width="450" height="450"></canvas>
Click Me!!
<br />
<img id="preview" />
Your code is fine and do not need any big change.
If you want to export image in various dimensions try this.
I created two export links, one for width 500 and one for 1000.
As you see you can export image directly instead of canvas.
var canvas = new fabric.Canvas('canvas');
document.getElementById('file').addEventListener("change", function (e) {
var file = e.target.files[0];
var reader = new FileReader();
reader.onload = function (f) {
var data = f.target.result;
fabric.Image.fromURL(data, function (img) {
var oImg = img.set({left: 50, top: 100, angle: 00}).scale(0.9);
canvas.add(oImg);
});
};
reader.readAsDataURL(file);
});
document.querySelector('#txt').onclick = function (e) {
_export(e, 500);
}
document.querySelector('#txt2').onclick = function (e) {
_export(e, 1000);
}
function _export(e, width) {
e.preventDefault();
var a = canvas.getActiveObject();
canvas.deactivateAll().renderAll();
var mult = width / a.width;
document.querySelector('#preview').src = a.toDataURL({multiplier: mult});
}
canvas {
border: 1px solid black;
}
<script src="https://rawgit.com/kangax/fabric.js/master/dist/fabric.min.js"></script>
<input type="file" id="file">
<canvas id="canvas" width="400" height="400"></canvas>
Click Me!! 500<br />
Click Me!! 1000
<br />
<img id="preview" />
See if https://jsfiddle.net/8gt6d7op/14/ works. toDataURL only works with whatever is in the canvas, so you can't specify size. Size is already in the canvas.
You can use a 2nd canvas with a size you want and use that to populate the image from.
<script src="https://rawgit.com/kangax/fabric.js/master/dist/fabric.min.js"></script>
<input type="file" id="file">
<canvas id="canvas" width="400" height="400"></canvas>
Click Me!!
<br />
<img id="preview" />
<canvas id="canvas2" width="1000" height="1000" style="display:none;"></canvas>
var canvas = new fabric.Canvas('canvas');
var canvas2 = new fabric.Canvas('canvas2');
document.getElementById('file').addEventListener("change", function (e) {
var file = e.target.files[0];
var reader = new FileReader();
reader.onload = function (f) {
var data = f.target.result;
fabric.Image.fromURL(data, function (img) {
var oImg = img.set({left: 50, top: 100, angle: 00}).scale(0.9);
canvas.add(oImg).renderAll();
canvas2.add(oImg).renderAll();
var a = canvas.setActiveObject(oImg);
var dataURL = canvas2.toDataURL({format: 'png', quality: 0.8});
console.log("aaaaaaaaaaa" + dataURL);
// console.log("Canvas Image " + dataURL);
// document.getElementById('txt').href = dataURL;
});
};
reader.readAsDataURL(file);
});
document.querySelector('#txt').onclick = function (e) {
e.preventDefault();
canvas2.deactivateAll().renderAll();
document.querySelector('#preview').src = canvas2.toDataURL();
}
I am using HTML5 and fabric js for uploading multiple image in canvas. Right now i am uploading multiple image in canvas. But i want to find uploaded image width and height. I have seen one link Check image width and height before upload with Javascript
In this link not using file reader. But in my case using file reader.
var canvas = new fabric.Canvas('canvas');
document.getElementById('file').addEventListener("change",function (e) {
var file = e.target.files[0];
var reader = new FileReader();
console.log("reader " + reader);
reader.onload = function (f) {
var data = f.target.result;
fabric.Image.fromURL(data, function (img) {
var oImg = img.set({ width: 250, height: 200, angle: 0}).scale(0.9);
canvas.add(oImg).renderAll();
var a = canvas.setActiveObject(oImg);
var dataURL = canvas.toDataURL({format: 'png', quality: 0.8});
});
};
reader.readAsDataURL(file);
});
canvas{
border: 1px solid black;
}
<script src="https://rawgit.com/kangax/fabric.js/master/dist/fabric.min.js"></script>
<input type="file" id="file">
<div style="">
<canvas id="canvas" width="450" height="450"></canvas>
</div>
You can create an img tag and get the dimensions from it.
document.getElementById('file').addEventListener("change",function (e) {
var file = e.target.files[0];
var reader = new FileReader();
var output = document.getElementById('output');
reader.onload = function (f) {
var data = f.target.result;
var img = document.createElement('img');
img.src = data;
img.onload = function() {
output.innerHTML = 'width: ' + img.width + '\n' +
'height: ' + img.height;
};
};
reader.readAsDataURL(file);
});
<input type="file" id="file"/>
<pre id="output"></pre>
#jcubic is right about using an <img> tag, (while there would be some ways to get this info without it) but he is absolutely wrong in how he gets the image's dimensions.
.clientWidth and .clientHeight will return the computed width of the <img> element. You don't care about it, since what you are drawing on your canvas is the image contained in the <img>, not the <img> element itself.
What you need then is .width and .height properties or .naturalWidth and .naturalHeight.
document.getElementById('file').addEventListener("change",function (e) {
var file = e.target.files[0];
var reader = new FileReader();
var output = document.getElementById('output');
reader.onload = function () {
var data = this.result;
var img = new Image();
img.src = data;
img.onload = function() {
output.innerHTML = 'width: ' + img.width + '\n' +
'height: ' + img.height;
};
};
reader.readAsDataURL(file);
});
<input type="file" id="file"/>
<pre id="output"></pre>