Resize a fabricjs rect to maintain border size - javascript

I would like to resize a fabricjs rect instead of scale it, but I'm seeing weird behaviour while dragging the resize handles. The border starts to disappear or duplicate. I've tried both the stable version 1.7.19 and the beta 2.0.0 of fabricjs.
Here is the essence of the code I'm using:
canvas.on('object:scaling', function(){
var obj = canvas.getActiveObject(),
width = obj.width,
height = obj.height,
scaleX = obj.scaleX,
scaleY = obj.scaleY;
obj.set({
width : width * scaleX,
height : height * scaleY,
scaleX: 1,
scaleY: 1
});
});
Working example here: https://codepen.io/bramchi/pen/GMLYEV/
Try scaling it up and down a bit by dragging the resize handles.
Screenshot of scaling up and down issues
What I would expect to happen is the rectangle growing and shrinking while dragging the handles, and the border size to stay the same. But somehow rendering starts to go bonkers if you cross 270px or so. When the mouse button is released, it renders properly again.
What am I doing wrong? Who knows a fix? Or could this be a bug in the library I can report?

Disable object caching to avoid this rendering behaviour:
fabric.Object.prototype.objectCaching = false;
For performance reasons Fabric.js caches objects by default during drag rotate skew and scale operations. One of the moderators of the fabric.js repo pointed me in the right direction, hooray for him!

as described here:
http://fabricjs.com/fabric-object-caching ( really last line )
disabling noScaleCache is enough.
That gives you caching anyway, just it invalidates cache everytime you scale the object.
Not that caching a rect is that usefull, but if you have the same behaviour for complex paths, that is still a good thing to have.
new fabric.Rect({
left: 50,
top: 50,
width: 250,
height: 250,
stroke: 'gray',
fill: 'lightgray',
strokeWidth: 10,
noScaleCache: false,
})

Related

Resizing a canvas element via dragging the edges

I'm trying to make it so users of my site can resize their canvas by simply dragging the sides of it. I'm using Fabric.js which allows me to resize elements from within the canvas but I need to resize the actual canvas itself. I'm fine with using any new libraries you recommend.
This image should help you understand a bit more of what I want.
As a side note, the Fabric.js team have an interactive toolbox here for you to experiment if you need it.
Put your fabric.js canvas in a wrapper div.
Make the wrapper resizable. Here I'm using CSS resize. It only adds a bottom-left corner as a resize control but it's good enough for the sake of the demo. To have all the edges as controls you can try something like this.
Detect the wrapper's size change. Ideally, you would use something like ResizeObserver. However, since browser support is still about 80% at the time of posting this, you might feel the need to use a polyfill or write something specific to your case. A simple setInterval with size check might prove to be sufficient.
When the wrapper's size changes, set new fabric.js canvas dimensions via setWidth() and setHeight().
const canvas = new fabric.Canvas('c')
canvas.add(new fabric.Rect({
width: 100,
height: 100,
fill: 'red',
left: 100,
top: 50,
}))
const canvasWrapper = document.getElementById('wrapper')
// initial dimensions
canvasWrapper.style.width = '300px'
canvasWrapper.style.height = '150px'
let width
let height
setInterval(() => {
const newWidth = canvasWrapper.clientWidth
const newHeight = canvasWrapper.clientHeight
if (newWidth !== width || newHeight !== height) {
width = newWidth
height = newHeight
canvas.setWidth(newWidth)
canvas.setHeight(newHeight)
}
}, 100)
#wrapper {
border: solid 1px black;
resize: both;
overflow: hidden;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/3.6.2/fabric.min.js"></script>
<div id="wrapper">
<canvas id="c"></canvas>
</div>
This isn't something that's going to be easy, but it's definitely possible. First, you may wonder about the native browser element resize CSS property and ResizeObserver, however those have poor support right now. Your best option is to:
Create a canvas element
Detect mousemoves on the canvas:
If the mousemove happens around the edge of the canvas, set the cursor to be the resize icon in the proper direction
If the mouse is currently down, resize the canvas based on the mouse's position.
Remember that every time you resize a canvas, the current image on the canvas is wiped.

Animate along motionpath in responsive SVG

I'm trying to make an animation with greensock. I want to move a balloon over a painted line and the graphic/animation shall be scalable.
I have a problem to align the balloon svg to the painted line. As soon as the browser width does not equal the svgs viewport width, the animation does not work. I'm pretty sure that's not the real spirit of scalable (!) vector graphics. So what am i doing wrong? How can I align the balloon to the line, also when the svg's size is changing?
Here is a simplified codepen of the little project:
TweenMax.to("#balloon", 3, {
bezier: {
values: MorphSVGPlugin.pathDataToBezier("#Path23",{
//matrix:[1.5,0,0,1.5,0,scaleX+"%"],
offsetX: -50,
offsetY: -50,
align:"#balloon"}),
type: "cubic"
},
ease: Linear.easeNone,
repeat: -1,
force3D: true
});
CodePen
The problem was, that i was using two svgs instead of one container. Also the transformOrigin made it work in the end. I updated the codepen. Now it works.

how to make rectangle scale vertically animation in Raphael JS

The Raphael Js website is down so I can't find any documentation or anything on how to do this. I want to create a rectangle with initial vertical size of 0 and make it animate so that it gets vertically larger and larger when I click another object. Thanks!
so i've got a rectangle
var water = paper.rect( 0, 300, 600, 0).attr({fill:"blue"});
how do I make it animate?
In particular, check out the documentation for
Element.attribute(),
Element.animate(),
Element.click(), and
Raphael.animation().
The following snippet demonstrates a simple animation like the one you are looking for. Click the red square to make the water "fill". It may not work in some browsers (e.g. Chrome) possibly because the snippet is trying to access an external third-party library, i.e. Raphael.js. So, to run it, either go to this SO question/answer page on Firefox or copy the code and run it on your own computer.
Note that, to make the water "fill" in the up direction, you can't just increase the height of the water rectangle...that would make the rectangle grow downwards. You also have to simultaneously raise the top of the rectangle by the identical amount. Thus you have to animate height and y simultaneously, as shown in the code.
UPDATE: provided an up-to-date link for the Raphael minified library
var paper = Raphael(0, 0, 500, 120);
var button = paper.rect( 10, 10, 40, 20).attr({fill:"red"});
var water = paper.rect( 10, 100, 400, 0).attr({fill:"blue"});
var anim = Raphael.animation({
height: 60,
y: (100 - 60)
}, 2000);
button.click(function() {water.animate(anim);});
<script src="https://raw.githubusercontent.com/DmitryBaranovskiy/raphael/master/raphael.min.js"></script>
To get the animation to start, click on the red rectangle.

KineticJS draggable image stuck after drag

I am using KineticJS and to this point it has been a great experience. One question I have though is about dragging. I have the image in this example set to 'draggable: true', but after I drag it the first time, it cannot be moved again.
var stage = new Kinetic.Stage({
container: 'container',
width: 2754,
height: 1836
});
var layer = new Kinetic.Layer();
var scale = '0.16339869281045751633986928104575';
var imageObj = new Image();
imageObj.onload = function () {
var img = new Kinetic.Image({
x: 0,
y: 0,
height:612,
width:612,
image: imageObj,
draggable: true,
dragBoundFunc: function (pos) {
console.log(img.getAttrs());
return {
x: Math.floor((pos.x/scale)/306)*306,
y: Math.floor((pos.y/scale)/306)*306
};
}
});
// add the shape to the layer
layer.add(img);
// add the layer to the stage
stage.add(layer);
};
imageObj.src = 'http://www.html5canvastutorials.com/demos/assets/yoda.jpg';
http://jsfiddle.net/7UEC6/
Any help is appreciated. For extra credit you can suggest ways to make the dragging smoother in general.
Thanks!
edit: I have noticed that after the image is dragged the initial time, the dragBoundFunc is no longer called when the user tries to drag the image
it also works if i drag the image back to 0,0 but no other time
This is not possible with current KineticJS.
Let me try to explain why.
When you use transform:scale, which is CSS3 element(not standard yet), the visual position of actual elements gets also scaled. However the relative mouse position of MouseEvent only passes visual position(not scaled position).
The mouse click event for dragging, which KineticJS uses, only reads MouseEvent position, which is visual one(not scaled one), and it does not consider transformation of canvas element.
When you set your image x/y to following, you cannot even do the first drag
x: 612,
y: 612,
However when you set it as 0 and 0, it respond to it because the scaled and unscaled position is the same.
For the above example x/y 612 and 612, you cannot click to drag,
because KineticJS understand it as you are not clicking 612 and 612,
but it think it as 100 and 100
The reason is simple as I explained.
MouseEvent does not pass scaled X/Y, but visual position of X/Y.
Who knows when CSS3 become standard, it might be well supported :)
Meanwhile, I would not recommend to use transformation with canvas. Unless you build your own framework, it is pretty hard to make all things correctly with canvas transformed.

How can I use scrollbars to pan around a virtual canvas?

I want to create a jQuery plugin that implements a virtual HTML5 Canvas, i.e. a canvas that is physically no larger (or not much larger) that its appearance on the page. But the contents of what is intended to be shown on the canvas may be many times larger that the canvas and will be dynamically redrawn on depending on scrollbars.
You would think that this is very common functionality, but so far i have not been able to find examples either with jQuery plugins or otherwise. This is very similar to what e.g. SlickGrid does for a Div, except this is with a Canvas. I can think of two solutions:
Use a jQuery UI Slider to implement a scrollbar as a completely separate element and use its event to control the Canvas redrawing.
Do whatever it is SlickGrid does for the Div. It appears to make a Div that is slightly larger than what is being displayed and the hook up to scroll events to dynamically add/remove element to/from the Div. But I can't see how it modifies the scrollbar to make it appear as if there is much more in the Div that what is currently being displayed.
What would you recommend? Sample code would be greatly appreciated.
I dug into the SlickGrid code and used method 2) (sort of) - it was something like this I had in mind:
/*
jensk#migselv.com
Simple virtual CANVAS controlled by a native scrollbar made with two DIVs
Uses jCanvas by Caleb Evans (http://calebevans.me/projects/jcanvas/index.php)
Thanks to Michael Leibman of SlickGrid fame for ideas.
Still need to clean it up (get rid of hardcoded values) and make it a nice, configurable
jQuery component.
Currently also redraws the entire canvas on each scroll event. Could be optimized to
do real browser scrolling and only redrawing the needed parts.
Another gotcha is that since it is the zero width DIVs that causes the scroll events,
mouse wheel, trackpad, touchscreen etc. scrolling over the Canvas will not work - only
the scrollbar is active. To solve this, one could make the Canvas larger inside a
smaller DIV too, catch scroll events from it and perform redrawing and setting the DIV's
scrollTop accordingly.
*/
var h = 10000; // virtual canvas height
var vp = 400; // viewport height
var viewport, fakescrolldiv, canvas;
function onScroll() {
var scrollTop = viewport.scrollTop();
console.log("onScroll scrollTop=" + scrollTop);
$("canvas").clearCanvas();
// Red box top
$("canvas").drawRect({
fillStyle: "#F00",
x: 150,
y: 20 - scrollTop,
width: 100,
height: 100,
fromCenter: false
});
// Green box middle
$("canvas").drawRect({
fillStyle: "#0F0",
x: 150,
y: 140 - scrollTop,
width: 100,
height: 100,
fromCenter: false
});
// Blue box bottom
$("canvas").drawRect({
fillStyle: "#00F",
x: 150,
y: 260 - scrollTop,
width: 100,
height: 100,
fromCenter: false
});
var i = 0;
for (i = 0; i <= 396; i++) {
$("canvas").drawLine({
strokeStyle: "#000",
strokeWidth: 1,
x1: 0,
y1: i,
x2: (scrollTop + i) % 50,
y2: i
});
if ((scrollTop + i) % 50 === 0) {
$("canvas").drawText({
fillStyle: "#729fcf",
text: (scrollTop + i).toString(),
align: "left",
baseline: "top",
font: "normal 12pt Verdana",
x: 60,
y: i
});
}
}
}
$(function() {
viewport = $("#viewport");
fakescrolldiv = $("#fakescrolldiv");
canvas = $("#gfx");
viewport.css("height", vp);
fakescrolldiv.css("height", h);
viewport.scroll(onScroll);
viewport.trigger("scroll");
});
Live demo
Any suggestions for improvements or simplifications are greatly appreciated.
From my personal experience your option (1) is an attractive choice, but there might be some interesting points in making it into a useable jQuery plugin.
I've been working on a financial data visualisation system that explicitly uses HTML5 Canvas for graph and chart drawing. We have different virtual 'scenes' or 'slides' in the canvas which 'slide in' and 'slide out' in the canvas, much like the same way you'd navigate in a big virtual canvas. All the event handling buttons are exclusively drawn on the canvas which dictate which screen we'd be showing, but we have a one/two normal HTML forms that take user inputs and brings those 'slides'. We use jQuery to handle events from these text boxes, but the jQuery codes are deeply nested inside the other Canvas drawing codes, (unlike an externalised call, which would be an idea candidate for making a plugin).
Sliding or updating the canvas is another thing. This is because not only it depends on the jQuery event that triggers the update but it also depends on the Canvas Framework (plain code or KineticJS, EaselJS, jCotton etc) that is responsible for the update. If you use a framework, you'll need to interface with the framework as well.
For simplicity let's assume that there is a callback function that you can call for that Canvas framework with parameters like movement offset (x, y), and the framework will add/remove this offset to the x and y positions of all the objects drawn in the canvas, most Canvas drawing frameworks also have a render() function that it calls periodically so that next time it draws the scene the results will automatically show (in your case, scrolling through the virtual canvas).
So it basically comes down to not only writing it as a jQuery plugin but also a binding it to a particular Canvas Framework e.g. KineticJS or others.
If you use basic Canvas functions instead of using any of those Frameworks, then it's another story, you can write your own render and update functions for the canvas, but in that case it'll be restricting the potential user to adhere the limitations of your drawing functions, unless you expose an API to extend them; but then again, that means you are writing your own Canvas framework :)
I'm not sure if I understood your problem correctly, in that case you can safely ignore my advice :), but If I'm right, my opinion would be: making a plugin like this would require also binding to a Canvas framework to make it really useable.
Hope it helps.

Categories

Resources