Fabricjs responsive canvas items issues - javascript

i'm having some issues when the canvas width and height changes, i want the items to be in there same position..
i' using the latest version of fabricjs and using pdfjs library with it..
here's the code i'm using to try to fix it, but not working unfortunately:
function rescale_canvas_if_needed() {
var optimal_dimensions = [$(".canvasWrapper").outerWidth(), $(".canvasWrapper").outerHeight()];
var scaleFactorX = window.innerWidth / optimal_dimensions[0];
var scaleFactorY = window.innerHeight / optimal_dimensions[1];
if (scaleFactorX < scaleFactorY && scaleFactorX < 1) {
canvas.setWidth(optimal_dimensions[0] * scaleFactorX);
canvas.setHeight(optimal_dimensions[1] * scaleFactorX);
canvas.setZoom(scaleFactorX);
} else if (scaleFactorX > scaleFactorY && scaleFactorY < 1) {
canvas.setWidth(optimal_dimensions[0] * scaleFactorY);
canvas.setHeight(optimal_dimensions[1] * scaleFactorY);
canvas.setZoom(scaleFactorY);
} else {
canvas.setWidth(optimal_dimensions[0]);
canvas.setHeight(optimal_dimensions[1]);
canvas.setZoom(1);
}
canvas.calcOffset();
canvas.renderAll();
}
function handle_resize() {
$(".canvas-container").hide();
rescale_canvas_if_needed();
$(".canvas-container").show();
}
to test it: try adding an drawing on the book and click on the zoom in and out and see how the canvas items position is changing.

I am going to make the assumption that you've calculated the scale factor correctly - I'd either have to think really critically about the scaleFactorX and scaleFactorY idea or just play with code (of which I am too lazy to do at this moment), but you may only need to check for 1 of them for scaling:
function rescale_canvas_if_needed() {
var optimal_dimensions = [$(".canvasWrapper").outerWidth(), $(".canvasWrapper").outerHeight()];
// add a rectangle the size of the current canvas and center it
rect = new fabric.Rect({
left: 0,
top: 0,
width: canvas.width,
height: canvas.height,
angle: 0,
fill: 'rgba(255,255,255,0)',
transparentCorners: true
});
canvas.add(rect);
rect.center();
// get an active selection of all objects
canvas.discardActiveObject();
var sel = new fabric.ActiveSelection(canvas.getObjects(), {canvas: canvas});
canvas.setActiveObject(sel);
canvas.requestRenderAll();
// scale your canvas
var scaleFactorX = window.innerWidth / optimal_dimensions[0];
var scaleFactorY = window.innerHeight / optimal_dimensions[1];
if (scaleFactorX < scaleFactorY && scaleFactorX < 1) {
canvas.setWidth(optimal_dimensions[0] * scaleFactorX);
canvas.setHeight(optimal_dimensions[1] * scaleFactorX);
canvas.setZoom(scaleFactorX);
} else if (scaleFactorX > scaleFactorY && scaleFactorY < 1) {
canvas.setWidth(optimal_dimensions[0] * scaleFactorY);
canvas.setHeight(optimal_dimensions[1] * scaleFactorY);
canvas.setZoom(scaleFactorY);
} else {
canvas.setWidth(optimal_dimensions[0]);
canvas.setHeight(optimal_dimensions[1]);
canvas.setZoom(1);
}
canvas.calcOffset();
// scale the active selection to the new width
sel.scaleToWidth(canvas.width);
// center the selection
sel.center();
// deselect the active selection
canvas.discardActiveObject();
// delete the rectangle
canvas.remove(rect);
canvas.requestRenderAll();
}
function handle_resize() {
// I don't think you should have to hide or show the canvas-container
$(".canvas-container").hide();
rescale_canvas_if_needed();
$(".canvas-container").show();
}
This will discard any active selections on the page before resizing it - maybe thats how you will want it, but you could get the active selection before resizing everything, then once it is done with all the resizing, reselect that active selection.
Warning: I didn't test this, so it may have a bug, invalid syntax, or other problems within that nature.
Let me know if you can't past another hurtle, given this bit of code.

Related

svg-pan-zoom pan/zoom to any object

I'm using the svg-pan-zoom code https://github.com/ariutta/svg-pan-zoom to make an svg map of some kind, now it is time to add a feature to pan & zoom to an art component of the svg on a click event. However, I'm not sure how to use the panBy() function to get to a desired svg art item: I tried to use the getBBox() on the group I'm looking to pan to and use that with the panZoomInstance.getPan() and getSizes() information, but my experiments are not working out.
I'd like to accomplish the same king of animation as their example (http://ariutta.github.io/svg-pan-zoom/demo/simple-animation.html) but center the viewport to the item.
Against all odds I was able to figure out this part of it!
function customPanByZoomAtEnd(amount, endZoomLevel, animationTime){ // {x: 1, y: 2}
if(typeof animationTime == "undefined"){
animationTime = 300; // ms
}
var animationStepTime = 15 // one frame per 30 ms
, animationSteps = animationTime / animationStepTime
, animationStep = 0
, intervalID = null
, stepX = amount.x / animationSteps
, stepY = amount.y / animationSteps;
intervalID = setInterval(function(){
if (animationStep++ < animationSteps) {
panZoomInstance.panBy({x: stepX, y: stepY})
} else {
// Cancel interval
if(typeof endZoomLevel != "undefined"){
var viewPort = $(".svg-pan-zoom_viewport")[0];
viewPort.style.transition = "all " + animationTime / 1000 + "s ease";
panZoomInstance.zoom(endZoomLevel);
setTimeout(function(){
viewPort.style.transition = "none";
$("svg")[0].style.pointerEvents = "all"; // re-enable the pointer events after auto-panning/zooming.
panZoomInstance.enablePan();
panZoomInstance.enableZoom();
panZoomInstance.enableControlIcons();
panZoomInstance.enableDblClickZoom();
panZoomInstance.enableMouseWheelZoom();
}, animationTime + 50);
}
clearInterval(intervalID)
}
}, animationStepTime)
}
function panToElem(targetElem) {
var initialSizes = panZoomInstance.getSizes();
var initialLoc = panZoomInstance.getPan();
var initialBounds = targetElem.getBoundingClientRect();
var initialZoom = panZoomInstance.getZoom();
var initialCX = initialBounds.x + (initialBounds.width / 2);
var initialCY = initialBounds.y + (initialBounds.height / 2);
var dX = (initialSizes.width / 2) - initialCX;
var dY = (initialSizes.height / 2) - initialCY;
customPanByZoomAtEnd({x: dX, y: dY}, 2, 700);
}
The key was in calculating the difference between the center of the viewport width & height from panZoomInstance.getSizes() and the center of the target element's client bounding rectangle.
Now the issue is trying to make an animated zoom. For now I've made it do a zoom to a specified location with a command at the end of the panning animation and set some css to make the zoom a smooth transition. The css gets removed after some time interval so normal zooming and panning isn't affected. In my attempts to make the zoom a step animation it always appeared to zoom past the intended max point.

How to make width and height of a rectangle updates after resize in fabric js?

I want to contain the rectangles within the image and wrote the following code. It does not work after resize because the width and height of the active object doesn't seem to update after resize.
This is the jsfiddle: https://jsfiddle.net/yxchng/0hL2khro/191/
canvas.on("object:moving", function(opt) {
activeObject = canvas.getActiveObject()
if (activeObject.left < 0) {
activeObject.left = 0;
}
if (activeObject.top < 0) {
activeObject.top = 0;
}
if (activeObject.left + activeObject.width > 1000) {
activeObject.left = 1000 - activeObject.width;
}
if (activeObject.top + activeObject.height > 1000) {
activeObject.top = 1000 - activeObject.height;
}
activeObject.setCoords();
});
Is there a better way to contain objects within image?
If you consider only scaling (not skewing);
Updated values will be
height = object.height * object.scaleY;
width = object.width * object.scaleX;
For fabricjs V 2.x
Use getScaledHeight and getScaledWidth which returns height and width of object bounding box counting transformations respectively.

RevealJS and Highchart Mouse position Tooltip Issue

I've just built my first RevealJS presentation and while all seemed to work at glance I ran into an game breaking issue with a HighChart that is caused by the way RevealJS scales/moves and elements and SVG related (at least I think so).
There's a similar issue report here, at least it seems related, though I've been unable to resolve my issue as the suggested code is not a drop-in and I'm my JS skills are lacking at best ->
Mouse position in SVG and RevealJS
I was hoping someone could help me pinpoint a potential solution, maybe that of the other stack easily can be adapted (I do need the scaling function, I know I could initialize RevealJS with a percentage option, but that will effectively break scaling on any smaller devices).
This is the code part that seems related, in my case the second else if( scale > 1 && features.zoom ) { ... } is triggered and the scaling creates a bad offset depending on resolution.
var size = getComputedSlideSize();
// Layout the contents of the slides
layoutSlideContents( config.width, config.height );
dom.slides.style.width = size.width + 'px';
dom.slides.style.height = size.height + 'px';
// Determine scale of content to fit within available space
scale = Math.min( size.presentationWidth / size.width, size.presentationHeight / size.height );
console.log("Size:"+size.presentationWidth);
console.log("Size:"+size.width);
console.log("1:"+scale);
// Respect max/min scale settings
scale = Math.max( scale, config.minScale );
console.log("2:"+scale);
scale = Math.min( scale, config.maxScale );
console.log("3:"+scale);
// Don't apply any scaling styles if scale is 1
if( scale === 1 ) {
dom.slides.style.zoom = '';
dom.slides.style.left = '';
dom.slides.style.top = '';
dom.slides.style.bottom = '';
dom.slides.style.right = '';
transformSlides( { layout: '' } );
}
else {
// Prefer zoom for scaling up so that content remains crisp.
// Don't use zoom to scale down since that can lead to shifts
// in text layout/line breaks.
if( scale > 1 && features.zoom ) {
dom.slides.style.zoom = scale;
dom.slides.style.left = '';
dom.slides.style.top = '';
dom.slides.style.bottom = '';
dom.slides.style.right = '';
transformSlides( { layout: '' } );
}
// Apply scale transform as a fallback
else {
dom.slides.style.zoom = '';
dom.slides.style.left = '50%';
dom.slides.style.top = '50%';
dom.slides.style.bottom = 'auto';
dom.slides.style.right = 'auto';
transformSlides( { layout: 'translate(-50%, -50%) scale('+ scale +')' } );
}
}
I've created a codepen to illustrate the issue, resize it from small to max size and check the mouse tooltip, there will be a small to massive offset between where the mouse is and what tooltip point shows except when the scale is 1:1.
https://codepen.io/anon/pen/MVLazG
Any and all help would be welcome. If there's a way to process the graph in a way that would retain a better mouse position I'd be grateful both suggestions and code (banged my head for a couple of hours on different approaches without luck).
It is caused by setting transform's scale on the wrapping div. You can read more about on Highcharts github here.
There is a workaround for this which seems to work in your example:
Highcharts.wrap(Highcharts.Pointer.prototype, 'normalize', function (proceed, event, chartPosition) {
var e = proceed.call(this, event, chartPosition);
var element = this.chart.container;
if (element && element.offsetWidth && element.offsetHeight) {
var scaleX = element.getBoundingClientRect().width / element.offsetWidth;
var scaleY = element.getBoundingClientRect().height / element.offsetHeight;
if (scaleX !== 1) {
e.chartX = parseInt(e.chartX / scaleX, 10);
}
if (scaleY !== 1) {
e.chartY = parseInt(e.chartY / scaleY, 10);
}
}
return e;
});
live example: https://codepen.io/anon/pen/GxzPKq

Realistic mouse movement coordinates in javascript?

In javascript, is there a way I can create a variable and a function that "simulates" smooth mouse movement? i.e., say the function simulates a user starts from lower left corner of the browser window, and then moves mouse in a random direction slowly...
The function would return x and y value of the next position the mouse would move each time it is called (would probably use something like setInterval to keep calling it to get the next mouse position). Movement should be restricted to the width and height of the screen, assuming the mouse never going off of it.
What I don't want is the mouse to be skipping super fast all over the place. I like smooth movements/positions being returned.
A "realistic mouse movement" doesn't mean anything without context :
Every mouse user have different behaviors with this device, and they won't even do the same gestures given what they have on their screen.
If you take an FPS game, the movements will in majority be in a small vertical range, along the whole horizontal screen.
Here is a "drip painting" I made by recording my mouse movements while playing some FPS game.
If we take the google home page however, I don't even use the mouse. The input is already focused, and I just use my keyboard.
On some infinite scrolling websites, my mouse can stay at the same position for dozens of minutes and just go to a link at some point.
I think that to get the more realistic mouse movements possible, you would have to record all your users' gestures, and repro them.
Also, a good strategy could be to get the coordinates of the elements that will attract user's cursor the more likely (like the "close" link under SO's question) and make movements go to those elements' coordinates.
Anyway, here I made a snippet which uses Math.random() and requestAnimationFrame() in order to make an object move smoothly, with some times of pausing, and variable speeds.
// Canvas is here only to show the output of function
var canvas = document.createElement('canvas');
var ctx = canvas.getContext('2d');
document.body.appendChild(canvas);
var maxX = canvas.width = window.innerWidth;
var maxY = canvas.height = window.innerHeight;
window.onresize = function(){
maxX = canvas.width = window.innerWidth;
maxY = canvas.height = window.innerHeight;
}
gc.onclick = function(){
var coords = mouse.getCoords();
out.innerHTML = 'x : '+coords.x+'<br>y : '+coords.y;
}
var Mouse = function() {
var that = {},
size = 15,
border = size / 2,
maxSpeed = 50, // pixels per frame
maxTimePause = 5000; // ms
that.draw = function() {
if (that.paused)
return;
that.update();
// just for the example
ctx.clearRect(0, 0, canvas.width, canvas.height);
if(show.checked){
ctx.drawImage(that.img, that.x - border, that.y - border, size, size)
}
// use requestAnimationFrame for smooth update
requestAnimationFrame(that.draw);
}
that.update = function() {
// take a random position, in the same direction
that.x += Math.random() * that.speedX;
that.y += Math.random() * that.speedY;
// if we're out of bounds or the interval has passed
if (that.x <= border || that.x >= maxX - border || that.y <= 0 || that.y >= maxY - border || ++that.i > that.interval)
that.reset();
}
that.reset = function() {
that.i = 0; // reset the counter
that.interval = Math.random() * 50; // reset the interval
that.speedX = (Math.random() * (maxSpeed)) - (maxSpeed / 2); // reset the horizontal direction
that.speedY = (Math.random() * (maxSpeed)) - (maxSpeed / 2); // reset the vertical direction
// we're in one of the corner, and random returned farther out of bounds
if (that.x <= border && that.speedX < 0 || that.x >= maxX - border && that.speedX > 0)
// change the direction
that.speedX *= -1;
if (that.y <= border && that.speedY < 0 || that.y >= maxY - border && that.speedY > 0)
that.speedY *= -1;
// check if the interval was complete
if (that.x > border && that.x < maxX - border && that.y > border && that.y < maxY - border) {
if (Math.random() > .5) {
// set a pause and remove it after some time
that.paused = true;
setTimeout(function() {
that.paused = false;
that.draw();
}, (Math.random() * maxTimePause));
}
}
}
that.init = function() {
that.x = 0;
that.y = 0;
that.img = new Image();
that.img.src ="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAB4AAAAeCAYAAAA7MK6iAAABJUlEQVRIic2WXbHEIAyFI6ESKgEJkVIJlYCTSqiESIiESqiEb19gL9Od3f5R5mbmPPHwBTgnIPJfChiAGbCkCQgtG7BpmgAWIALaDDyOI2bGuq40BasqIoKZATgwNAWHEEjHbkBsBhYRVJUYIwBNwVlFaVOwiDDPMylmQ1OwquY7d0CBrglYkuEeidoeOKt61I6Cq0ftKFhqR+0MOKuo2BQsInnndvnOr4JvR+0qWO5G7Q44K0XtOXDf96jqh9z9WXAy1FJ8l0qd+zbtvU7lWs7wIzkuh8SvpqqDi3zGndPQauDkzvdESm8xZvbh4mVZ7k8ud/+aR0C3YPk7mVvgkCZPVrdZV3dHVem6bju1roMPNmbAmq8kG+/ynD7ZwNsAVVz9dL0AhBrZq7F+CSQAAAAASUVORK5CYII=";
that.reset();
}
that.getCoords = function(){
return {x: that.x, y:that.y};
}
that.init()
return that;
}
var mouse = new Mouse()
mouse.draw();
html,body {margin: 0}
canvas {position: absolute; top:0; left:0;z-index:-1}
#out{font-size: 0.8em}
<label for="show">Display cursor</label><input name="show" type="checkbox" id="show" checked="true"/><br>
<button id="gc">get cursor Coords</button>
<p id="out"></p>
Last I heard the browser's mouse position cannot be altered with JavaScript, so the question really has no answer "as is". The mouse position can be locked though. I'm not certain whether it would be possible to implement a custom cursor that allows setting the position. This would include hiding and perhaps locking the stock cursor.
Having something smoothly follow the cursor is quite straight forward. You may be able to reverse this process to achieve what you need. Here's a code snippet which simply calculates the distance between the cursor and a div every frame and then moves the div 10% of that distance towards the cursor:
http://jsfiddle.net/hpp0qb0d/
var p = document.getElementById('nextmove')
var lastX,lastY,cursorX,cursorY;
window.addEventListener('mousemove', function(e){
cursorX = e.pageX;
cursorY = e.pageY;
})
setInterval(function(){
var newX = p.offsetLeft + (cursorX - lastX)/10
var newY = p.offsetTop + (cursorY - lastY)/10
p.style.left = newX+'px'
p.style.top = newY+'px'
lastX = p.offsetLeft
lastY = p.offsetTop
},20)

bounce check function for HTML5 canvas fails at corners

I have a HTML5 canvas that generates a bouncing box every time you click on it. The box array stores the x-value, y-value, x-velocity, and y-velocity of each box created. The box will travel in a random direction at first and will bounce of the sides of the canvas but if it hits a corner the box dissappears instead of bouncing back. EDIT: I answered my own question noticing that the soundY and soundX functions were causing the problem.
var box = new Array();
var width = window.innerWidth;
var height = window.innerHeight;
var field = document.getElementById('canvas');
field.width = width;
field.height = height;
field.ctx = field.getContext('2d');
field.ctx.strokeStyle = 'rgba(255,255,255,1)';
setInterval('redraw()', 200);
addEventListener('click', createBox, false);
function createBox(e) { // this box will always fail collision detection at the upper-left corner
box.push(100); // x-value is normally mouse position
box.push(100); // y-value is normally mouse position
box.push(-5); // x-speed is normally random
box.push(-5); // y-speed is normally random
}
function redraw() {
field.ctx.clearRect(0,0,width,height);
for(var i = 0; i < box.length; i+=4) {
if(box[i] < 0) { box[i+2] *= -1; soundY(box[i+1]); } // parameter of soundY is less than 0
else if(box[i] > width) { box[i+2] *= -1; soundY(box[i+1]); } // which is invalid and causes this to break
if(box[i+1] < 0) { box[i+3] *= -1; soundX(box[i]); }
else if(box[i+1] > height) { box[i+3] *= -1; soundX(box[i]); }
box[i] += box[i+2];
box[i+1] += box[i+3];
field.ctx.strokeRect(box[i], box[i+1], 4, 4);
}
}
function soundX(num) {
// play a sound file based on a number between 0 and width
}
function soundY(num) {
// play a sound file based on a number between 0 and height
}
The only way I could recreate the problem was by generating the box in one of the corners so that with the right x and y velocity the box was initially created outside the bounds of the canvas. When that happens, the inversion of the velocity isn't enough to bring the item back in bounds and so on the next frame the velocity is inverted again (and so on).
I think this might solve your problem:
var boxes = [];
var boxSize = 4;
var width = window.innerWidth;
var height = window.innerHeight;
var field = document.getElementById('canvas');
function redraw() {
field.ctx.clearRect(0, 0, width, height);
var box;
for (var i = 0; i < boxes.length; i++) {
box = boxes[i];
field.ctx.strokeRect(box.x, box.y, boxSize, boxSize);
if (box.x < 0) {
box.x = 0;
box.dx *= -1;
} else if (box.x > width - boxSize) {
box.x = width - boxSize;
box.dx *= -1;
}
if (box.y < 0) {
box.y = 0;
box.dy *= -1;
} else if (box.y > height - boxSize) {
box.y = height - boxSize;
box.dy *= -1;
}
box.x += box.dx;
box.y += box.dy;
}
}
field.width = width;
field.height = height;
field.ctx = field.getContext('2d');
field.ctx.strokeStyle = 'rgba(0,0,0,1)';
setInterval(redraw, 200);
addEventListener('click', createBox, false);
function createBox(e) {
boxes.push({
x: e.clientX - 10,
y: e.clientY - 10, // arbitrary offset to place the new box under the mouse
dx: Math.floor(Math.random() * 8 - boxSize),
dy: Math.floor(Math.random() * 8 - boxSize)
});
}
I fixed a few errors in your code and made some changes to make it a bit more readable (I hope). Most importantly, I extended your collision detection so that it resets the coordinates of the box to the bounds of your canvas should the velocity take it outside.
Created a jsfiddle which might be handy if further discussion is needed.
It was additional code (see edit) that I left out assuming it was unrelated to the issue, but removing the code solved the problem as it appears this use-case would cause an invalid input in this part of the code.

Categories