fabricJS: Scale canvas view - html

I have converted a pdf to image format using PDF.JS and rendered that to the canvas. While that process the rendered pdf image is showing blurred in the canvas.
I have no idea how to scale the image to some viewable format rather than being so blurred.
Image of the pdf in canvas:
Here in the image you can clearly see that the rendered image is not in readable format!
Here is the fiddle link: https://jsfiddle.net/kjxes63f/
var fabricCanvas;
fabricCanvas = new fabric.Canvas('firtcanvas');
document.querySelector("#pdf-upload").addEventListener("change", function (e) {
var file = e.target.files[0]
console.log("pdf evente");
console.log(e);
if (file.type != "application/pdf") {
console.error(file.name, "is not a pdf file.")
return
}
var fileReader = new FileReader();
fileReader.onload = function () {
var typedarray = new Uint8Array(this.result);
console.log("typedarray");
console.log(typedarray);
console.log("this.result");
console.log(this.result);
PDFJS.getDocument(typedarray).then(function (pdf) {
// you can now use *pdf* here
console.log("the pdf has ", pdf.numPages, "page(s).")
pdf.getPage(pdf.numPages).then(function (page) {
// you can now use *page* here
var viewport = page.getViewport(2.0);
var fabricCanvas = document.querySelector("#firtcanvas")
fabricCanvas.height = viewport.height;
fabricCanvas.width = viewport.width;
page.render({
canvasContext: fabricCanvas.getContext('2d'),
viewport: viewport
}).then(function () {
bg = fabricCanvas.toDataURL("image/png");
fabric.Image.fromURL(bg, function (img) {
img.scaleToHeight(800);
img.scaleToWidth(600);
console.log("img");
console.log(img);
console.log(bg);
var imgCanvas = img.set({ left: 0, top: 0, width: 150, height: 150 });
fabricCanvas.add(imgCanvas);
});
});
});
});
};
fileReader.readAsArrayBuffer(file);
});

Construction drawings are often wide-format and hard to read onscreen without zoom. As a work-around I'd suggest adding a zoom function to your canvas like below.
var canvas = new fabric.Canvas('pdfcanvas');
canvas.selection = false;
canvas.setHeight(450);
canvas.setWidth(636);
//zoom function
canvas.on('mouse:wheel', function(opt) {
var delta = opt.e.deltaY;
var pointer = canvas.getPointer(opt.e);
var zoom = canvas.getZoom();
zoom = zoom - delta / 200;
if (zoom > 10) zoom = 10;
if (zoom < 1) {
zoom = 1;
canvas.setViewportTransform([1, 0, 0, 1, 0, 0]);
}
canvas.zoomToPoint({
'x': opt.e.offsetX,
'y': opt.e.offsetY
}, zoom);
opt.e.preventDefault();
opt.e.stopPropagation();
});
//pdf load
document.querySelector('#pdf-upload').addEventListener('change', function(e) {
var pageEl = document.getElementById('page-container');
var file = e.target.files[0];
if (file.type == 'application/pdf') {
var fileReader = new FileReader();
fileReader.onload = function() {
var typedarray = new Uint8Array(this.result);
PDFJS.getDocument(typedarray).then(function(pdf) {
//console.log('the pdf has ', pdf.numPages, 'page(s).');
pdf.getPage(pdf.numPages).then(function(pageEl) {
var viewport = pageEl.getViewport(2.0);
var canvasEl = document.querySelector('canvas');
canvasEl.height = viewport.height;
canvasEl.width = viewport.width;
pageEl.render({
'canvasContext': canvasEl.getContext('2d'),
'viewport': viewport
}).then(function() {
var bg = canvasEl.toDataURL('image/png');
fabric.Image.fromURL(bg, function(img) {
canvas.setBackgroundImage(img);
});
});
});
});
};
fileReader.readAsArrayBuffer(file);
};
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/3.4.0/fabric.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/pdf.js/1.8.349/pdf.min.js"></script>
<input id="pdf-upload" type="file">
<div id="page-container">
<canvas id="pdfcanvas"></canvas>
</div>

Related

why i can't get full image size from convertToDataURLviaCanvas method in ionic 3?

I want original image size in offline mode also as shown in online mode in image 2.
My problem is that when i gone in app without internet connection, i loss full quality and size of images, because of i am using convertToDataURLviaCanvas().
so, please give here solution as soon as possible.
My code is:
I am using this function to convert all images:
convertToDataURLviaCanvas(url, outputFormat) {
return new Promise((resolve, reject) =>
{
let img = new Image();
img.crossOrigin = 'Anonymous';
img.onload = function () {
let canvas = <HTMLCanvasElement>document.createElement('CANVAS'),
ctx = canvas.getContext('2d'),
dataURL;
canvas.height = 1000;
canvas.width = 1000;
ctx.drawImage(img, 0, 0);
dataURL = canvas.toDataURL();
//callback(dataURL);
canvas = null;
resolve(dataURL);
};
img.src = url;
});
}
getTravelAdviceData() {
if(this.restProvider.getNetworkType() == 'none') {
// this.onlineGrid = false;
// this.offlineGrid = true;
this.storage.get('companyLogoOffline').then((data) => {
// Do something with latitude value
// console.log("offline data", data);
this.getcompanyLogo = data;
});
this.storage.get('travelTips64Image').then((data) => {
// Do something with latitude value
// console.log("offline data", data);
this.adviceArray = data;
// console.log("offline this.adviceArray", this.adviceArray);
});
} else {
// this.offlineGrid = false;
// this.onlineGrid = true;
this.restProvider.getTravelAdvice()
.then(data => {
let serviceData : any = data['consejosviaje'];
// this.adviceArray = serviceData;
let base64Image;
for (let i in serviceData) {
this.imagen = serviceData[i].imagen;
this.convertToDataURLviaCanvas(this.imagen, "image/jpeg").then(base64 => {
base64Image = base64;
this.texto = serviceData[i].texto;
this.adviceArrays64.push({'texto': this.texto, 'imagen': base64Image});
this.storage.set("travelTips64Image", this.adviceArrays64);
this.adviceArray = this.adviceArrays64;
});
}
});
}
}

How to apply z-index for fabric js handlers

setTimeout(function () {
var myImg = document.querySelector("#background");
var realWidth = myImg.naturalWidth;
var realHeight = myImg.naturalHeight;
$("canvas").attr("width", realWidth);
$("canvas").attr("height", realHeight);
var source = document.getElementById('background').src;
var canvas = new fabric.Canvas('canvas');
canvas.width = realWidth;
canvas.height = realHeight;
var ctx = canvas.getContext('2d');
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: 320
, top: 180
, angle: 00
, width: 200
, height: 200
});
canvas.add(oImg).renderAll();
var a = canvas.setActiveObject(oImg);
var dataURL = canvas.toDataURL({
format: 'png'
, quality: 0.8
});
});
};
reader.readAsDataURL(file);
});
canvas.setOverlayImage(source, canvas.renderAll.bind(canvas), {
backgroundImageOpacity: 0.5
, backgroundImageStretch: false
});
canvas.on('mouse:over', function (e) {
canvas.item(0).hasBorders = true;
canvas.item(0).hasControls = true;
canvas.setActiveObject(canvas.item(0));
});
canvas.on('mouse:out', function (e) {
canvas.item(0).hasBorders = false;
canvas.item(0).hasControls = false;
canvas.setActiveObject(canvas.item(0));
});
canvas.renderAll();
}, 2000);
$("#save").click(function () {
function blobCallback(iconName) {
return function (b) {
var a = document.getElementById('download');
a.download = iconName + ".jpg";
a.href = window.URL.createObjectURL(b);
}
}
canvas.toBlob(blobCallback('wallpaper'), 'image/vnd.microsoft.jpg', '-moz-parse-options:format=bmp;bpp=32');
});
.hide {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://cricmovie.com/bb-asserts/js/fabric.min.js"></script>
<body>
<div class="container"> <img src="http://cricmovie.com/bb-asserts/images/person.png" id="background" class="hide">
<input type="file" id="file">
<br />
<canvas id="canvas" class="img-responsive"></canvas>
</div>
<div class="container"> <a class="btn btn-primary" id="save">Save</a> <a class="btn btn-primary" id="download">Download</a> </div>
</body>
I am using fabric js to build a facemask application when i have two images
1) Image without face which is applied to canvas using setOverlayImage method
2) Only head where the user will upload and adjust accordingly.
I have almost done with functionality but I want to show fabric handlers above the first image where now they are hiding behind first image.
Reference Image : Click here for reference Image
Please find the Run Code Snippet
I think all you need to do is specify controlsAboveOverlay when you get the fabric instance.
var canvas = new fabric.Canvas('canvas', {
controlsAboveOverlay : true
});

Fabric.js canvas image disappear after loading image second time

Hello i am uploading a image once image will upload ,i am loading that image in canvas which i am creating in popup.
Once image is loaded it appears in pop up where i am performing crop functionality,everything is working fine but when i am uploading image second time
image appears but when i click on image to crop it image disappears on canvas.
Please suggest me how to fix the issue?
Here is my code
handleImage1= function(e) {
var mousex = 0;
var mousey = 0;
var reader = new FileReader();
var baseUrl = jQuery("#base-url").val();
var file = this.files[0];
var fd = new FormData();
fd.append("afile", file);
var mouseDown;
// only allow one crop. turn it off after that
var disabled = false;
var rect;
var container = document.getElementById('c1').getBoundingClientRect();
var canvas1 = new fabric.Canvas('c1');
var center = canvas1.getCenter();
//canvas1.add(rect);
var image;
var isDown, origX, origY;
var rawImageid;
var result='';
var object;
jQuery.ajax({
type : 'POST',
url : baseUrl+'personalized/index/saveRawImage',
data : fd,
dataType : 'text',
cache: false,
beforeSend: function(){
jQuery('#divLoading').show();
},
contentType: false,
processData: false,
success : function(result) {
result=result;
var imgSizeObj;
fabric.util.loadImage(result, function(img) {
image = new fabric.Image(img);
image.selectable = false;
image.originX= 'center',
image.originY= 'center',
//image.top=center.top,
//image.left=center.left,
imgSizeObj = image.getOriginalSize();
width_ratio = canvas1.width / image.width;
height_ratio = canvas1.height / image.height;
if (height_ratio>width_ratio ) {
fw = image.width * width_ratio;
fh = image.height*fw/image.width;
} else {
fh = image.height * height_ratio;
fw = image.width*fh/image.height;
}
if (imgSizeObj.width > canvas1.width || imgSizeObj.height > canvas1.height) {
image.set({
width: fw,
height: fh
});
}
canvas1.add(image);
canvas1.centerObject(image);
canvas1.renderAll();
});
// capture the event when the user clicks the mouse button down
canvas1.on('mouse:down', function(o){
isDown = true;
var pointer = canvas1.getPointer(o.e);
origX = pointer.x;
origY = pointer.y;
var pointer = canvas1.getPointer(o.e);
canvas1.remove(rect);
rect = new fabric.Rect({
left: origX,
top: origY,
originX: 'left',
originY: 'top',
width: pointer.x-origX,
height: pointer.y-origY,
angle: 0,
opacity:0.5,
transparentCorners: false,
hasControls: false,
hasBorders: false
});
canvas1.add(rect);
canvas1.renderAll()
});
// draw the rectangle as the mouse is moved after a down click
canvas1.on('mouse:move', function(o){
if (!isDown) return;
var pointer = canvas1.getPointer(o.e);
if(origX>pointer.x){
rect.set({ left: Math.abs(pointer.x) });
}
if(origY>pointer.y){
rect.set({ top: Math.abs(pointer.y) });
}
rect.set({ width: Math.abs(origX - pointer.x) });
rect.set({ height: Math.abs(origY - pointer.y) });
canvas1.renderAll();
});
canvas1.on('mouse:up', function(o){
isDown = false;
});
jQuery('#cropB').on('click', function() {
image.selectable = true;
disabled = true;
rect.visible = false;
var cropped = new Image();
cropped.src = canvas1.toDataURL({
left: rect.left,
top: rect.top,
width: rect.width,
height: rect.height
});
fabric.util.loadImage(cropped.src, function(img) {
var image1 = new fabric.Image(img);
image1.selectable = true;
canvas.add(image1);
canvas.centerObject(image1);
image1.selectable = true;
canvas.renderAll();
});
canvas1.clear();
jQuery('#changePic').modal('hide');
});
jQuery('#add_image_custom').on('click',function(){
var rawImageValue = jQuery("#rawImages").val();
rawImageid = result;
if(rawImageValue == 0){
rawImageValue = result;
}else{
rawImageValue = rawImageValue + ','+ result;
}
jQuery("#rawImages").val(rawImageValue);
var img = new Image();
var center = canvas.getCenter();
img.onload = function () {
var imgInstance = new fabric.Image(img, {
originX: 'center',
originY: 'center',
top: center.top,
left: center.left,
});
var imgSizeObj = imgInstance.getOriginalSize();
//alert(imgSizeObj.width+'|'+imgSizeObj.height+'|'+canvas.width+'|'+canvas.height);
width_ratio = canvas.width / imgSizeObj.width;
height_ratio = canvas.height / imgSizeObj.height;
if (height_ratio>width_ratio ) {
fw = imgSizeObj.width * width_ratio;
fh = imgSizeObj.height*fw/imgSizeObj.width;
} else {
fh = imgSizeObj.height * height_ratio;
fw = imgSizeObj.width*fh/imgSizeObj.height;
}
if (imgSizeObj.width > canvas.width || imgSizeObj.height > canvas.height) {
imgInstance.set({
width: fw,
height: fh
});
}
if(canvas.width<400)
{
imgInstance.scaleX = canvas.width*0.9/imgInstance.width;
imgInstance.scaleY = imgInstance.scaleX;
}
imgInstance.RawImageId=rawImageid;
canvas.add(imgInstance);
}
img.src = result;
reader.readAsDataURL(e.target.files[0]);
canvas1.clear();
jQuery('#changePic').modal('hide');
});
/*Shrink fit code end here---------------------------------*/
//imgpopup.src = src1;
//canvas1.add(image);
//canvas1.renderAll();
//jQuery('#main-image').attr('src',result);
//jQuery('#main-image').show();
setTimeout(function(){
jQuery('#changePic').modal();
jQuery('#divLoading').hide();
}, 300);
},
error : function(xhr, status) {
//console.log(status);
//console.log(xhr); //
jQuery('.loading').hide();
}
});
}

How to render a blob on a canvas element?

How to render an image blob to a canvas element?
So far i have these two (simplified) functions to capture an image, transform it to a blob and eventually render the blob on a canvas
in this codepen, it just returns the default black image.
var canvas = document.getElementById('canvas');
var input = document.getElementById('input');
var ctx = canvas.getContext('2d');
var photo;
function picToBlob() {
var file = input.files[0];
canvas.toBlob(function(blob) {
var newImg = document.createElement("img"),
url = URL.createObjectURL(blob);
newImg.onload = function() {
ctx.drawImage(this, 0, 0);
photo = blob;
URL.revokeObjectURL(url);
};
newImg.src = url;
}, file.type, 0.5);
canvas.renderImage(photo);
}
HTMLCanvasElement.prototype.renderImage = function(blob) {
var canvas = this;
var ctx = canvas.getContext('2d');
var img = new Image();
img.onload = function() {
ctx.drawImage(img, 0, 0)
}
img.src = URL.createObjectURL(blob);
}
input.addEventListener('change', picToBlob, false);
I think you need to tidy up your code a bit. It's hard to know what you are trying to achieve because there are many unnecessary lines of code. The main problem is that blob is coming undefined here
HTMLCanvasElement.prototype.renderImage = function(blob){
because photo never gets initialized here inside the toBlob function...which is unnecessary for what you are trying to achieve.
Here's a simplified working version of your code snippet
var canvas = document.getElementById('canvas');
var input = document.getElementById('input');
function picToBlob() {
canvas.renderImage(input.files[0]);
}
HTMLCanvasElement.prototype.renderImage = function(blob){
var ctx = this.getContext('2d');
var img = new Image();
img.onload = function(){
ctx.drawImage(img, 0, 0)
}
img.src = URL.createObjectURL(blob);
};
input.addEventListener('change', picToBlob, false);
<input type='file' accept='image' capture='camera' id='input'>
<canvas id = 'canvas'></canvas>
You can also use createImageBitmap to directly render a blob into the canvas:
createImageBitmap(blob).then(imageBitmap=>{ctx.drawImage(imageBitmap,0,0)})
var canvas = document.getElementById('canvas');
var input = document.getElementById('input');
function blobToCanvas() {
createImageBitmap(input.files[0]).then(imageBitmap => {
console.log(imageBitmap);
canvas.getContext('2d').drawImage(imageBitmap, 0, 0)
})
}
input.addEventListener('change', blobToCanvas, false);
<input type='file' accept='image' capture='camera' id='input'>
<canvas id='canvas'></canvas>
You can use it as below
function renderImage(canvas, blob) {
const ctx = canvas.getContext('2d')
const img = new Image()
img.onload = (event) => {
URL.revokeObjectURL(event.target.src) // 👈 This is important. If you are not using the blob, you should release it if you don't want to reuse it. It's good for memory.
ctx.drawImage(event.target, 0, 0)
}
img.src = URL.createObjectURL(blob)
}
below is an example
/**
* #param {HTMLCanvasElement} canvas: https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API
* #param {Blob} blob: https://developer.mozilla.org/en-US/docs/Web/API/Blob
* */
function renderImage(canvas, blob) {
const ctx = canvas.getContext('2d')
switch (blob.type) {
case "image/jpeg": // Normally, you don't need it (switch), but if you have a special case, then you can consider it.
case "image/png":
const img = new Image()
img.onload = (event) => {
URL.revokeObjectURL(event.target.src) // Once it loaded the resource, then you can free it at the beginning.
ctx.drawImage(event.target, 0, 0)
}
img.src = URL.createObjectURL(blob)
break
}
}
// 👇 below is test
(() => {
const canvas = document.querySelector('canvas')
const input = document.querySelector('input')
input.addEventListener('change',
(event) => {
const file = event.target.files[0]
const blob = new Blob(
[file],
{"type": file.type} // If the type is unknown, default is empty string.
)
renderImage(canvas, blob)
}
)
})()
<div><input type='file' accept='.png,.jpg'></div>
<canvas></canvas>
another example to show you What effect of the revokeObjectURL.
<div></div>
<canvas width="477" height="600"></canvas>
<script>
async function renderImage(canvas, blob, isNeedRevoke=true) {
const ctx = canvas.getContext('2d')
const img = new Image() // The upper part of the painting.
const img2 = new Image() // The lower part of the painting.
await new Promise(resolve => {
img.onload = (event) => {
if (isNeedRevoke) {
URL.revokeObjectURL(event.target.src)
}
ctx.drawImage(event.target,
0, 0, 477, 300,
0, 0, 477, 300
)
resolve()
}
img.src = URL.createObjectURL(blob)
setTimeout(resolve, 2000)
}).then(() => {
img2.onload = (event) => {
ctx.drawImage(event.target,
0, 300, 477, 300,
0, 300, 477, 300
)
}
img2.src = img.src // 👈 If URL.revokeObjectURL(img.src) happened, then img2.src can't find the resource, such that img2.onload will not happen.
})
}
function CreateTestButton(canvas, btnText, isNeedRevoke) {
const button = document.createElement("button")
button.innerText = btnText
button.onclick = async (event) => {
canvas.getContext("2d").clearRect(0, 0, canvas.width, canvas.height) // clear canvas
fetch("https://upload.wikimedia.org/wikipedia/commons/thumb/6/6a/PNG_Test.png/477px-PNG_Test.png")
.then(async response=>{
const blob = await response.blob()
renderImage(canvas, blob, isNeedRevoke)
}).catch(err=>console.error(err))
}
return button
}
(() => {
window.onload = () => {
const canvas = document.querySelector('canvas')
const div = document.querySelector('div')
const btn1 = CreateTestButton(canvas, "Without URL.revokeObjectURL", false)
const btn2 = CreateTestButton(canvas, "URL.revokeObjectURL", true)
div.append(btn1, btn2)
}
})()
</script>

Can't get image width and height property from base64 data

I am uploading an image and i expect base64 data of that image.I am trying below code that works to get image data as base64.
1) function getImage(file,count) //file is files[i] of input:file passed from for()
{
if(file)
{
var reader = new FileReader();
reader.onload = function(event)
{
var data = event.target.result;
var image = document.createElement("img");
image.id = 'img'+count;
image.class = 'edit';
image.src = data;
console.log('width:'+this.width);//not working value is undefined
console.log('height:'+this.height);//not working value is undefined
//image.title = 'click to edit';
image.data = count;
data = image.dataset;
data.ref=count;
document.getElementById('image'+count).appendChild(image);
jQuery(document.getElementById('image'+count)).removeClass('disable');
jQuery(document.getElementById('img'+count)).addClass('action editable img ');
}
reader.readAsDataURL(file);
}
}
This works fine and it creates an img tag with image loaded correctly.
But I want to know the image width and height before creating img element, so i tried below code,
2) function getImage(file,count)
{
if(file)
{
var reader = new FileReader();
reader.onload = function(event)
{
var img = new Image();
var data = event.target.result;
img.onload = function(){
console.log(img.width);
var image = document.createElement("img");
image.id = 'img'+count;
image.class = 'edit';
image.src = data;
console.log('width:'+this.width);
console.log('height:'+this.height);
image.data = count;
data = image.dataset;
data.ref=count;
document.getElementById('image'+count).appendChild(image);
jQuery(document.getElementById('image'+count)).removeClass('disable');
jQuery(document.getElementById('img'+count)).addClass('action editable img ');
};
}
reader.readAsDataURL(file);
}
}
But the second code does not prints log and img tag is not created. so what is the problem?What wrong in my code?Any better way to achieve this?.
just single line makes my problem null,
Thanks to this.
function getImage(file,count)
{
if(file)
{
var reader = new FileReader();
reader.onload = function(event)
{
var img = new Image();
var data = event.target.result;
img.src = data; //this line solved my problem..
img.onload = function(){
var image = document.createElement("img");
image.id = 'img'+count;
image.class = 'edit';
image.src = data;
console.log('width:'+this.width);
console.log('height:'+this.height);
image.data = count;
data = image.dataset;
data.ref=count;
document.getElementById('image'+count).appendChild(image);
jQuery(document.getElementById('image'+count)).removeClass('disable');
jQuery(document.getElementById('img'+count)).addClass('action editable img ');
};
}
reader.readAsDataURL(file);
}
}
Waiting for any better answer..