Fabric JS Events On Canvas Objects - javascript

I'm loading a base 64 image into a canvas using the fabric.js API. What I need to be able to do is determine when an object on the canvas gets resized. I can't find any documentation on eventing on objects on a canvas. Is there a way to listen to events on these objects? Listening to resize on canvas or window is not working:
$("canvas").on("resize", function () {
console.log("Resize occurred"); //not called
});

What you are looking for here is not a resize event on the canvas, which will not trigger unless you resize the canvas element itself is, but a resize event on an object rendered on the canvas. Since you are using fabricjs to render your image you can listen to fabricjs events to get your desired result. Overview of all fabricjs events you can find here. In your case object:scaled would be the event to listen to. The following runnable code snippet illustrates an example:
const canvas = new fabric.Canvas('canvas', {
selection: false
});
const imageElement = document.getElementById('image');
const img = new fabric.Image(imageElement, {
left: 20,
top: 20,
scaleX: 1,
scaleY: 1
});
canvas.add(img);
canvas.on('object:scaled', (options) => {
console.log(
"Object was scaled, current scaleX:",
options.target.scaleX,
" and scaleY: ",
options.target.scaleX)
});
canvas {
border: 1px solid #000;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/3.4.0/fabric.min.js"></script>
<canvas id="canvas" width="300" height="200"></canvas>
<img style="display: none" id="image" src="https://images.unsplash.com/photo-1507146426996-ef05306b995a?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=200&q=80" />

Related

Getting current cursor position on the clicked object in Fabric.js

I am developing a Web application that involves HTML canvas feature. I am using Fabric.JS - http://fabricjs.com/ to render objects on it. In Fabric.Js, I can implement event listeners to the object as in this link- http://fabricjs.com/.
I am now adding an image object to the canvas and implement the mouse event listener to that image object. When the image object on the canvas is clicked, I would like to retrieve the position (x, y) of the image clicked. But it is always returning zero.
I am adding image object to the canvas like this:
var imgInstance = new fabric.Image(js_left_temp_img, {
left: 0,
top: 0
});
imgInstance.scale(0.1)
imgInstance.selectable = false;
imgInstance.set('selectable', false)
$canvas.add(imgInstance);
Then I set up the event listener to the image object like this and try to retrieve the clicked position of image object like this.
imgInstance.on('mousedown', function(e){
//alert('Image clicked')
console.log(e.target.left + " - " + e.target.top)
});
When I click on the image, it fires the event, but the left and top values are always returning zero. How can I retrieve the current clicked left and top or x and y position of the image in the event listener?
Use object.getLocalPointer()
DEMO
var canvas = new fabric.Canvas('canvas'),imgInstance;
canvas.on('object:selected', function(e) {
});
fabric.Image.fromURL('http://fabricjs.com/assets/pug.jpg', function(img) {
img.set({
left: 0,
top: 0,
scaleX: 0.3,
scaleY: 0.3
});
canvas.add(img);
img.on('mousedown',function(options){
var pointer = this.getLocalPointer(options.e);
console.log(pointer);
})
});
canvas{
border:2px solid #000;
}
<script src="https://rawgit.com/kangax/fabric.js/master/dist/fabric.js"></script>
<canvas id='canvas' width=500 height=400>

not able to draw rect on existing <canvas> which rendered PDF using pdfjs

Task
Have a canvas in your page
<canvas id="pdfCanvas">
create a fabric canvas for existing canvas
new fabric.Canvas("pdfCanvas");
have mouse.down, mouse.up, mouse.move methods to enable drawing rectangles
render pdf in the above canvas "pdfCanvas" using PDF.js
browser now shows the rendered PDF
now draw rectangles on the pdf, it hides the rendered canvas but it does draw objects
Problem
Here is the fiddle to see the issue:
- run the above https://jsfiddle.net/hiitskiran/wgz8qore/2/
- you can see the fabric rectangle is hiding behind the rendered pdf
- click on the pdf canvas area to see the fabric objects
What I see from your fiddle is that you don't wait the result of page.render method, which is asyncronous, then, unfortunately, if you wait the page.render, the fabric.canvas instance will clean your previously filled canvas, and we can't do nothing for this.
So I tried another approach: First of all, I wait the pdf.js page.render method, then I invoke the .toDataURL of your previously filled canvas so that I can have a copy of the old content, then I set your previously filled canvas as background of your new fabric.canvas and finish to draw your rectangle.
var url = 'http://www.africau.edu/images/default/sample.pdf';
var canvas = document.getElementById('pdfcanvas');
var context = canvas.getContext('2d');
PDFJS.disableWorker = true;
PDFJS.getDocument(url).then(function(pdf) {
pdf.getPage(1).then(function(page) {
var scale = 1.5;
var viewport = page.getViewport(scale);
canvas.height = viewport.height;
canvas.width = viewport.width;
page.render({
canvasContext: context,
viewport: viewport
}).then(function() {
var bg = canvas.toDataURL("image/png");
var fcanvas = new fabric.Canvas("pdfcanvas", {
selection: false
});
fcanvas.setBackgroundImage(bg,fcanvas.renderAll.bind(fcanvas));
fcanvas.setWidth(300);
fcanvas.setHeight(300);
var rect = new fabric.Rect({
left: 100,
top: 100,
width: 50,
height: 50,
fill: '#FF454F',
opacity: 0.5,
transparentCorners: true,
borderColor: "gray",
cornerColor: "gray",
cornerSize: 5
});
fcanvas.add(rect);
fcanvas.renderAll();
});
});
});
<script src="https://rawgit.com/kangax/fabric.js/master/dist/fabric.js"></script>
<script src="https://seikichi.github.io/tmp/PDFJS.0.8.715/pdf.min.js"></script>
<canvas id="pdfcanvas" style="border:1px solid black"></canvas>

How to save Zoomed and Panned Canvas to dataUrl in Javascript

I build a canvas Element in which you can zoom and pan a background image and by click you can add Icons on it. It is built on fabric js.
So once I added icons and zoomed and panned, I would like to save the image to dataurl. If I just use canvas.toDataURL, I can only see the currently shown area. Does anybody have an Idea, how I can save the entire area of the background image with all elements on the canvas? I therefore need a function, which resets the zoom and the pan and adjusts the size of the canvas to the size of the background image.
I included an example of how initialized my canvas below.
// New Fabric Canvas
var canvas = new fabric.Canvas('c'); //render image to this canvas
window.addEventListener('resize', resizeCanvas, false);
function resizeCanvas() {
canvas.setHeight(window.innerHeight);
canvas.setWidth(window.innerWidth);
canvas.renderAll();
}
// resize on init
resizeCanvas();
// Load image
var image = new Image();
image.onload = function() {
loadImage(image, canvas);
canvas.height = image.height;
canvas.width = image.width;
}
function loadImage(image, canv) {
var img = new fabric.Image(image, {
selectable: false,
lockUniScaling: true,
centeredScaling: true,
alignX: "mid",
alignY: "mid",
});
canv.add(img);
canv.centerObject(img);
}
image.src = 'http://placehold.it/350x150';
<script src="http://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.1.0/fabric.all.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="canvasarea" style="background: #000;">
<canvas id='c' onclick="return false;"></canvas>
</div>
If you just want to generate an image and not change the zoom level of canvas, you can pass multiplier parameter to toDataUrl function.
var dataURL = canvas.toDataURL({
format: 'png',
multiplier: 2
});
This will generate an image after zooming in 200%.
You can even specify the part of the canvas, you want to generate an image of by using:
var dataURL = canvas.toDataURL({
format: 'png',
left: 100,
top: 100,
width: 200,
height: 200
});
Check the details here, toDataUrl function:
http://fabricjs.com/docs/fabric.Canvas.html

Recreate Fabric.js canvas and export as an image?

I have a canvas where the user can create a design using images in another div that they click, sending it to the Fabric.js canvas where it gets moved around and so on. Since the canvas's size is width="270"and height="519", smaller than what the finished product is, I need to recreate it with a canvas that has the size width="1001"and height="1920" and then screenshot it so that I get it all in 1 single image. How do I do this?
This is what my code looks like so far:
HTML
<div id="CanvasContainer">
<canvas id="Canvas" width="270" height="519"></canvas>
</div>
CSS
#CanvasContainer {
width: 270px;
height: 519px;
margin-left: 15px;
}
#Canvas {
overflow: hidden;
}
JAVASCRIPT
//Defining Canvas and object array
var canvas = new fabric.Canvas('Canvas');
//When clicked
$(document).ready(function () {
$("#Backgrounds img").click(function () {
var getId = $(this).attr("id");
//adding all clicked images
var imgElement = document.getElementById(getId);
var imgInstance = new fabric.Image(imgElement, {
left: 135,
top: 259,
width: 270,
height: 519
});
//Corner color for clicked images
imgInstance.set({
borderColor: 'white',
cornerColor: 'black',
transparentCorners: false,
cornerSize: 12
});
canvas.add(imgInstance);
});
});
Fabric has a built in function to convert to data urls. You can use the download property of a link to make the link a download link. Finally you can use the DOM click() function to emulate clicking the download link. The end result is:
function download(url,name){
// make the link. set the href and download. emulate dom click
$('<a>').attr({href:url,download:name})[0].click();
}
function downloadFabric(canvas,name){
// convert the canvas to a data url and download it.
download(canvas.toDataURL(),name+'.png');
}
now when you want to download the canvas call
downloadFabric(canvas,'<file name>');

Bind event to shape on canvas

How can I bind an event to a shape drawn on a canvas? I presumed this would work but I get an error.
<html>
<head>
<script type="application/javascript">
function draw() {
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
ctx.fillStyle = "rgb(200,0,0)";
var rec = ctx.fillRect (0, 0, 55, 50);
rec.onclick = function(){
alert('something');
}
}
</script>
</head>
<body onLoad="draw()">
<canvas id="canvas" width="300" height="300"></canvas>
</body>
</html>
Put the event handlers on the canvas element, and then use the mouse position to decide which conceptual part of the canvas the event is occurring on.
I haven't played with canvas all that much, but I wouldn't be surprised if there were already some libraries that help you manage event delegation to such imaginary elements.
Using Kineticsjs, you can handle shape events in a canvas as follows:
<script>
shape.on('mousedown mouseover' function(evt) {
// do something
});
</script>
Sounds like you should be using svg instead since it allows you to add event listeners on shapes. I'd recommend checking out raphaeljs.com for a start.

Categories

Resources