Pop-Up Window, Center Screen - google-chrome-extension

I'm using the following code to open a pop-up window in a Google Chrome extension, my one question is, how do I get the pop-up window to open in the centre of the users screen?
<script>
chrome.browserAction.onClicked.addListener(function() {
var left = (screen.width/2)-(w/2);
var top = (screen.height/2)-(h/2);
chrome.windows.create({'url': 'redirect.html', 'type': 'popup', 'width': 440, 'height': 220, 'left': '+left+', 'top': '+top+', } , function(window) {
});
});
</script>
I've also tried this, which resulted in no such luck.
<script>
chrome.browserAction.onClicked.addListener(function() {
chrome.windows.create({'url': 'redirect.html', 'type': 'popup', 'width': 440, 'height': 220, 'left': (screen.width/2)-(w/2), 'top': (screen.height/2)-(h/2), } , function(window) {
});
});
</script>

When you see var obj = {property: value} structure in JS it is an object creation. In your code you are trying to pass an object containing window properties to chrome.windows.create() function.
Correct code should be:
chrome.browserAction.onClicked.addListener(function() {
var w = 440;
var h = 220;
var left = (screen.width/2)-(w/2);
var top = (screen.height/2)-(h/2);
chrome.windows.create({'url': 'redirect.html', 'type': 'popup', 'width': w, 'height': h, 'left': left, 'top': top} , function(window) {
});
});

If you want the centering to also work with a dual monitor, you'll need to get the current window object from the extension and center your popup relative to that. Like so:
chrome.browserAction.onClicked.addListener(function() {
chrome.windows.getCurrent(function(win) {
var width = 440;
var height = 220;
var left = ((screen.width / 2) - (width / 2)) + win.left;
var top = ((screen.height / 2) - (height / 2)) + win.top;
chrome.windows.create({
url: 'redirect.html',
width: width,
height: height,
top: Math.round(top),
left: Math.round(left),
type: 'popup'
});
});
});
chrome.windows.create expects an integer for top and left, so it is recommended to wrap those values in Math.round.

If you want the screen to appear in the middle of the browser (not the center of the screen), and dynamic window size, you can do this.
chrome.windows.getCurrent((tabWindow) => {
const width = Math.round(tabWindow.width * 0.5) // dynamic width
const height = Math.round(tabWindow.height * 0.75) // dynamic height
const left = Math.round((tabWindow.width - width) * 0.5 + tabWindow.left)
const top = Math.round((tabWindow.height - height) * 0.5 + tabWindow.top)
chrome.windows.create( // https://developer.chrome.com/docs/extensions/reference/windows/#method-create
{
focused: true,
url: targetURL,
type: 'popup', // https://developer.chrome.com/docs/extensions/reference/windows/#type-WindowType
width, height,
left, top
},
(subWindow) => {}
)
})
Desc
Image
Show you what is the tabWindow.top and left
And you can use some filters to check whether the window has been created or not, to determine to create a new one, or show the window that you made.
chrome.windows.getAll({populate : true, windowTypes:['popup']}, (windowArray)=>{})
example code
chrome.windows.getCurrent((tabWindow) => { // https://developer.chrome.com/docs/extensions/reference/windows/#type-Window
const targetURL = 'yourTemplates/yourFile.html'
chrome.windows.getAll({populate : true, windowTypes:['popup']}, (windowArray)=>{
const queryURL = `chrome-extension://${chrome.runtime.id}/${targetURL}`
const target = windowArray.find(item=>item.tabs[0].url === queryURL) // ❗ make sure manifest.json => permissions including "tabs"
if (windowArray.length > 0 && target !== undefined) {
// Show the window that you made before.
chrome.windows.update(target.id, {focused: true}) // https://developer.chrome.com/docs/extensions/reference/windows/#method-update
return
}
// Otherwise, Create
const width = Math.round(tabWindow.width * 0.5)
const height = Math.round(tabWindow.height * 0.75)
const left = Math.round((tabWindow.width - width) * 0.5 + tabWindow.left)
const top = Math.round((tabWindow.height - height) * 0.5 + tabWindow.top)
chrome.windows.create( // https://developer.chrome.com/docs/extensions/reference/windows/#method-create
{
focused: true,
url: targetURL,
type: 'popup', // https://developer.chrome.com/docs/extensions/reference/windows/#type-WindowType
width, height,
left, top
},
(subWindow) => {
}
)
})
})

As an addendum to this answer, if you want to retrieve popup dimensions from localstorage--which are saved as strings--this will convert the variables to the necessary integers for the pop-up to work.
var w = parseInt(localStorage.getItem('key'));
var h = parseInt(localStorage.getItem('key'));

Related

Pixi.js How should HP write?

How should HP write?
Because HP will decrease, but I found that he will deform.
Each time container.hpStatus.width- = 1; HP's icon will be distorted, especially HP = 0 is most obvious.
enter image description here
You Can Look My Codepen.
app.ticker.add((delta) => {
if (container.hpStatus.width > 0) {
container.hpStatus.width -= 1;
} else {
container.hpStatus.width = 450;
}
});
How can i make sure he doesn't deform?
The hp bar is getting distorted because you are decreasing width of "container.hpStatus" which is Geometry object which is itself a Container:
https://pixijs.download/dev/docs/PIXI.Graphics.html#Graphics
And as you see in docs of the "width" property: https://pixijs.download/dev/docs/PIXI.Container.html#width
width number
The width of the Container, setting this will actually modify the scale to achieve the value set
It means that changing "width" scales whole container ("container.hpStatus").
To draw such hp bar without "distortion" you can do it by drawing hp bar on each "tick" (each frame).
Plaese check following code - is your example but modified. Most important parts are "createHpBar" function and modified "main loop" (ticker).
(i also added some comments so you can understand better)
and here is updated codepen: https://codepen.io/domis86/pen/poJrKdq
const app = new PIXI.Application({
view: document.getElementById('main'),
width: 900,
height: 900,
antialias: true,
transparent: false,
backgroundColor: 0x00CC99,
});
// See: https://pixijs.download/dev/docs/PIXI.Ticker.html
let ticker = PIXI.Ticker.shared;
ticker.autoStart = false;
const container = new PIXI.Container();
app.stage.addChild(container);
function createHpBar(currentHp, maxHp, color) {
let hpBar = new PIXI.Graphics();
hpBar.beginFill(color);
let hpPortion = currentHp / maxHp;
hpBar.drawPolygon([
50, 80,
50 + (400 * hpPortion), 80,
32 + (400 * hpPortion), 150,
32, 150,
]);
hpBar.endFill();
return hpBar;
}
// Create black hp bar (the one behind the red one) and add it to our container:
let blackHpBar = createHpBar(450, 450, 0x000000);
container.addChild(blackHpBar);
container.x = 100;
container.y = 200;
let renderer = app.renderer;
// Starting amount of hp:
var currentHp = 450;
ticker.add((delta) => {
// create red hp bar which is a polygon with vertices calculated using "currentHp" amount:
let redHpBar = createHpBar(currentHp, 450, 0xFF0000);
// add red hp bar to container:
container.addChild(redHpBar);
// render our stage (render all objects from containers added to stage)
// see https://pixijs.download/dev/docs/PIXI.Ticker.html#.shared
renderer.render(app.stage);
// Remove red hp bar from our container:
// We do this because on next tick (aka: next frame) we will create new redHpBar with "createHpBar" (as you see above)
container.removeChild(redHpBar);
// Update current hp amount:
if (currentHp > 0) {
currentHp -= 1;
} else {
currentHp = 450;
}
});
// start rendering loop:
ticker.start();

OWL 2.2.0 Is it possible to see only the item active center and hide slides before and after?

2.0 and I would like to see only one slide which is the class: "owl-item active center"
Could you help me?
thank you and have a good day
jQuery script :
var owl = $('.owl-carousel');
$(".owl-carousel").each(function(index, el) {
var containerHeight = $(el).height();
$(el).find("img").each(function (index, img) {
var w = $(img).prop('naturalWidth');
var h = $(img).prop('naturalHeight');
$(img).css({
'width': Math.round(containerHeight * w / h) + 'px',
'height': containerHeight + 'px'
});
})
});
// Carousel initialization
owl.owlCarousel({
center: true,
loop:false,
margin:0,
singleItem:true,
autoWidth: true,
navSpeed:500,
nav:true,
autoplay: false,
rewind: true,
items:1
});**strong text**
enter image description here

signature-pad - resize not working

i'm using the signature-pad plugin and i'm having some issues whith the resize event:
- Multiple resizes lead to a loss in quality and the signature "moves" at each resize of the browser window ending with no signature in canvas.
- In some cases, the isEmpty() function wont work and i'll be able to save the empty signature.
Optional question : how can i detect an empty signature on php side ?
Thank you :)
Below my code :
$(window).resize(function() {
resizeCanvas();
});
var wrapper1 = document.getElementById("signature-pad"),
clearButton1 = wrapper1.querySelector("[data-action=clear]"),
canvas1 = wrapper1.querySelector("canvas"),
signaturePad1;
var wrapper2 = document.getElementById("signature-pad-paraphe"),
clearButton2 = wrapper2.querySelector("[data-action=clear]"),
canvas2 = wrapper2.querySelector("canvas"),
signaturePad2;
// Adjust canvas coordinate space taking into account pixel ratio,
// to make it look crisp on mobile devices.
// This also causes canvas to be cleared.
signaturePad1 = new SignaturePad(canvas1);
signaturePad2 = new SignaturePad(canvas2);
function resizeCanvas() {
//Sauvegarde sig / par
var sig = signaturePad1.toDataURL();
var par = signaturePad2.toDataURL();
var ratio = Math.max(window.devicePixelRatio || 1, 1);
canvas1.width = canvas1.offsetWidth * ratio;
canvas1.height = canvas1.offsetHeight * ratio;
canvas1.getContext("2d").scale(ratio, ratio);
canvas2.width = canvas2.offsetWidth * ratio;
canvas2.height = canvas2.offsetHeight * ratio;
canvas2.getContext("2d").scale(ratio, ratio);
// redraw
signaturePad1.fromDataURL(sig);
signaturePad2.fromDataURL(par);
}
window.onresize = resizeCanvas;
resizeCanvas();
// Init -> retourne la bonne valeur de isEmpty -> !!? Not sure if needed
signaturePad1.clear();
signaturePad2.clear();
var signature = $('#confirm_delete_signature').val();
if(signature){
signaturePad1.fromDataURL(signature);
}
var paraphe = $('#confirm_delete_paraphe').val();
if(paraphe){
signaturePad2.fromDataURL(paraphe);
}
clearButton1.addEventListener("click", function (event) {
signaturePad1.clear();
});
clearButton2.addEventListener("click", function (event) {
signaturePad2.clear();
});
Here is i developed a little solution;
Here are two key DOM elements:
div#id_wrapper
canvas#id
Considered it may be applied at devices with different devicePixelRatio and on screens changins theirs width (f.i.: portrait-landscape orientation).
export class FlexSignatureComponent extends React.Component {
state = {
width: 0,
lines: [],
storedValue: undefined,
validationClass: '', // toggles between 'is-invalid'/'is-valid'
validationMessage: ''
}
The lib initiation is right after the component got loaded:
componentDidMount = () => {
this.signPad = new SignaturePad(document.getElementById(this.props.htmlid), {
onEnd: this.onChangeSignaturePad,
backgroundColor: '#fff'
});
if (this.valueHolder.current.value) {
const data = JSON.parse(this.valueHolder.current.value);
this.state.lines = data.value;
this.state.width = 100;
}
//you need the next workarounds if you have other onWidnowResize handlers manarging screen width
//setTimeout-0 workaround to move windowResizeHandling at the end of v8-enging procedures queue
// otherwise omit setTimeout and envoke func as it is
setTimeout(this.handleWindowResize, 0);
window.addEventListener("resize", () => setTimeout(this.handleWindowResize, 0));
}
First handle window resize change
handleWindowResize = () => {
if (this.state.storedValue) {
const prevWrapperWidth = this.state.width;
const currentWrapperWidth = $(`#${this.props.htmlid}_wrapper`).width();
const scale = prevWrapperWidth / currentWrapperWidth;
this.state.width = currentWrapperWidth;
this.setRescaledSignature(this.state.lines, scale);
this.resetCanvasSize();
this.signPad.fromData(this.state.lines)
} else
this.resetCanvasSize()
}
Second rescaleSignature to another width
setRescaledSignature = (lines, scale) => {
lines.forEach(line => {
line.points.forEach(point => {
point.x /= scale;
point.y /= scale;
});
});
}
Finally updated canvas size
resetCanvasSize = () => {
const canvas = document.getElementById(this.props.htmlid);
canvas.style.width = '100%';
canvas.style.height = canvas.offsetWidth / 1.75 + "px";
canvas.width = canvas.offsetWidth * devicePixelRatio;
canvas.height = canvas.offsetHeight * devicePixelRatio;
canvas.getContext("2d").scale(devicePixelRatio, devicePixelRatio);
}
Here we on every change add new drawn line to this.state.lines
and prepare the lines to be submited as json.
But before the submission they need to create deepCopy and to be rescaled to conventional size (its width is equal 100px and DPR is 1)
onChangeSignaturePad = () => {
const value = this.signPad.toData();
this.state.lines = value;
const currentWrapperWidth = $(`#${this.props.htmlid}_wrapper`).width();
const scale = currentWrapperWidth / 100;
const ratio = 1 / devicePixelRatio;
const linesCopy = JSON.parse(JSON.stringify(value));
this.setRescaledSignature(linesCopy, scale, ratio);
const data = {
signature_configs: {
devicePixelRatio: 1,
wrapper_width: 100
},
value: linesCopy
};
this.state.storedValue = JSON.stringify(data);
this.validate()
}
One more thing is the red button to swipe the previous signatures
onClickClear = (e) => {
e.stopPropagation();
this.signPad.clear();
this.valueHolder.current.value = null;
this.validate()
}
render() {
let {label, htmlid} = this.props;
const {validationClass = ''} = this.state;
return (
<div className="form-group fs_form-signature">
<label>{Label}</label>
<div className="fs_wr-signature">
<button className={'fs_btn-clear'} onClick={this.onClickClear}>
<i className="fas fa-times"></i>
</button>
<div id={htmlid + '_wrapper'} className={`w-100 fs_form-control ${validationClass}`}>
<canvas id={htmlid}/>
</div>
</div>
<div className={' invalid-feedback fs_show-feedback ' + validationClass}>Signature is a mandatory field</div>
</div>
)
}
postWillUnmount() {
this.signPad.off();
}
the used lib signature pad by szimek
Used React and Bootstrap and some custome styles
the result would be
You didn't provide a full example, or much explanation of the code, so it's hard to tell what all is going on here, but I'll do my best to give as full an answer as I can.
Saving
First, if I understand the docs correctly, $(window).resize will be triggered at the same time as window.onresize. You use both. That might be causing some issues, maybe even the issues with saving.
The following code is run once, and I'm not sure what it's supposed to do:
var signature = $('#confirm_delete_signature').val();
if(signature){
signaturePad1.fromDataURL(signature);
}
var paraphe = $('#confirm_delete_paraphe').val();
if(paraphe){
signaturePad2.fromDataURL(paraphe);
}
It looks like it's supposed to be deleting the signature (since the selector is #confirm_delete_signature), but it instead, it's restoring a signature from some data stored in the node as a string. That might be causing issues too.
That said, I'm not sure why saving isn't working, but I can't find the code of your saving function, so it's very hard to say. Maybe I missed something.
I'm not familiar with php, sorry.
Resizing
For resizing, I think the React version that #Alexey Nikonov made might work with React (I didn't run it). You have to scale the positions of the points of the lines along with the changing size of the canvas.
I wanted a version closer to vanilla js, so I recreated it with just signature_pad v4.1.4 and jQuery at https://jsfiddle.net/j2Lurpd5/1/ (with an improvement to ratio calculation).
The code is as follows, though it doesn't have a button to clear the canvas:
<div id="wrapper">
<canvas id="pad" width="200" height="100"></canvas>
</div>
canvas {
border: red 1px solid;
}
// Inspiration: https://stackoverflow.com/a/60057521
// Version with no React
const canvas = document.querySelector('#pad');
const signPad = new SignaturePad(canvas);
// Doesn't work without the #wrapper. Probably because #pad
// needs it to be able to be 100% of it. Not sure exactly
// why that makes a difference when #wrapper doesn't have
// a width set on it. Though #pad alone does work after the
// first resize.
let prevWidth = $('#wrapper').width();
let lines = [];
setTimeout(resizeSignatureAndCanvas, 0);
window.addEventListener("resize", () => setTimeout(resizeSignatureAndCanvas, 0));
window.addEventListener("orientationchange", () => setTimeout(resizeSignatureAndCanvas, 0));
function resizeSignatureAndCanvas () {
// Get the current canvas contents
lines = signPad.toData();
// if there are no lines drawn, don't need to scale them
if ( signPad.isEmpty() ) {
// Set initial size
resizeCanvas();
} else {
// Calculate new size
let currentWidth = $('#wrapper').width();
let scale = currentWidth / prevWidth;
prevWidth = currentWidth; // Prepare for next time
// Scale the contents along with the width
setRescaledSignature(lines, scale);
// Match canvas to window size/device change
resizeCanvas();
// Load the adjusted canvas contents
signPad.fromData(lines);
}
};
// This is really the key to keeping the contents
// inside the canvas. Getting the scale right is important.
function setRescaledSignature (lines, scale) {
lines.forEach(line => {
line.points.forEach(point => {
// Same scale to avoid warping
point.x *= scale;
point.y *= scale;
});
});
};
function resizeCanvas () {
/** Have to resize manually to keep the canvas the width of the
* window without distorting the location of the "pen". */
// I'm not completely sure of everything in here
const canvas = $('#pad')[0];
// Not sure why we need both styles and props
canvas.style.width = '100%';
canvas.style.height = (canvas.offsetWidth / 1.75) + 'px';
// When zoomed out to less than 100%, for some very strange reason,
// some browsers report devicePixelRatio as less than 1
// and only part of the canvas is cleared then.
let ratio = Math.max(window.devicePixelRatio || 1, 1);
// This part causes the canvas to be cleared
canvas.width = canvas.offsetWidth * ratio;
canvas.height = canvas.offsetHeight * ratio;
canvas.getContext("2d").scale(ratio, ratio);
};
As you can see from my notes, I'm not completely sure why every part works, but from what I can tell it does preserve the behavior of the version that #Alexey Nikonov made.

How to add Header and footer content to pdfkit for node.js

I would like to generate a pdf using node js (express). I need to add header and footer to every page with page numbers. Any help would be appreciated.
Thanks.
Adding a Footer on all pages
doc.addPage()
let bottom = doc.page.margins.bottom;
doc.page.margins.bottom = 0;
doc.text('Page 1', 0.5 * (doc.page.width - 100), doc.page.height - 50,
{
width: 100,
align: 'center',
lineBreak: false,
})
// Reset text writer position
doc.text('', 50, 50)
doc.page.margins.bottom = bottom;
let pageNumber = 1;
doc.on('pageAdded', () => {
pageNumber++
let bottom = doc.page.margins.bottom;
doc.page.margins.bottom = 0;
doc.text(
'Pág. ' + pageNumber,
0.5 * (doc.page.width - 100),
doc.page.height - 50,
{
width: 100,
align: 'center',
lineBreak: false,
})
// Reset text writer position
doc.text('', 50, 50);
doc.page.margins.bottom = bottom;
})
You can do this :
doc.text('This is a footer', 20, doc.page.height - 50, {
lineBreak: false
});
Adding content to every page using doc.on('pageAdded'... hook has the nasty side effect of hijacking your position (doc.x/doc.y) while filling in a page. Additionally, you have to set the autoFirstPage: false flag in order to inject your hook prior to first page creation.
I find using bufferPages mode and then making global edit to the pages at the end much more graceful/logical.
const doc = new PDFDocument({
bufferPages: true
});
doc.text("Hello World")
doc.addPage();
doc.text("Hello World2")
doc.addPage();
doc.text("Hello World3")
//Global Edits to All Pages (Header/Footer, etc)
let pages = doc.bufferedPageRange();
for (let i = 0; i < pages.count; i++) {
doc.switchToPage(i);
//Header: Add page number
let oldTopMargin = doc.page.margins.top;
doc.page.margins.top = 0 //Dumb: Have to remove top margin in order to write into it
doc
.text(
`Page: ${i + 1} of ${pages.count}`,
0,
(oldTopMargin/2), // Centered vertically in top margin
{ align: 'center' }
);
doc.page.margins.top = oldTopMargin; // ReProtect top margin
//Footer: Add page number
let oldBottomMargin = doc.page.margins.bottom;
doc.page.margins.bottom = 0 //Dumb: Have to remove bottom margin in order to write into it
doc
.text(
`Page: ${i + 1} of ${pages.count}`,
0,
doc.page.height - (oldBottomMargin/2), // Centered vertically in bottom margin
{ align: 'center' }
);
doc.page.margins.bottom = oldBottomMargin; // ReProtect bottom margin
}
doc.end();
about this library, I suggest to read the PDF documentation, it is a lot must complete that the online HTML doc.
Warning : To be able to write outside the main content area, you have to set height and width on text's function params.
so as seen pdf doc you can do :
const doc = new PDFDocument({bufferPages: true})
//addPage X times
const range = doc.bufferedPageRange();
for( let i = range.start; i < (range.start + range.count); i++) {
doc.switchToPage(i);
doc.text(`Page ${i + 1} of ${range.count}`,
200,
doc.page.height - 40,
{ height : 25, width : 100});
}
this works for me
const doc = new PDFDocument({bufferPages: true})
const range = doc.bufferedPageRange();
for (let i = range.start; i <= (doc._pageBufferStart +
doc._pageBuffer.length - 1); i++) {
doc.switchToPage(i);
doc.font('Times-Roman').fontSize(8).text('Footer', 90,
doc.page.height - 40, {
lineBreak: false
});
}

Applying clipTo path on image in fabric.js incorrectly repositions the image

Please take a look at this fiddle:
http://jsfiddle.net/2ktvyk4e/5/
var imgUrl, snapshotCanvas;
imgUrl = 'http://cdn-development.wecora.com/boards/backgrounds/000/001/388/cover/ocean-background.jpg';
snapshotCanvas = new fabric.StaticCanvas('snapshotCanvas', {
backgroundColor: '#e0e0e0',
width: 1000,
height: 1500
});
fabric.Image.fromURL(imgUrl, function(img) {
img.set({
width: 1000,
left: 0,
top: 0,
clipTo: function(ctx) {
return ctx.rect(0, 0, 1000, 400);
}
});
return snapshotCanvas.add(img).renderAll();
}, {
crossOrigin: 'Anonymous'
});
It's pretty simple. I'm loading an image and then trying to clip it so that the full width of the canvas but clipped so only the top 400 pixels are showing. For some reason, the clipTo causes the image to move and resize inexplicably:
As you can see, when the clipping path is applied the image is repositioned on the canvas inexplicably. If I remove the clipTo, then the image loads full canvas width no problem (of course its also full height, which we don't want).
I have no idea what is happening here or why this is occuring so any help is appreciated.
Make sure you have originX and originY left to top and left on both the canvas and your image. Also - you don't really need to clip anything to the canvas. The only real use I've found for clipTo was clipping collage images to their bounding shapes. If you want to restrict the image from being dragged above that 400px, I would recommend rendering a rectangle below it (evented = false, selectable = false) and then clipping to that rectangle.
I put this together without clipTo (and changed some numbers so I wasn't scrolling sideways). It renders the image half way down the canvas.
http://jsfiddle.net/2ktvyk4e/6/
Edit:
I dug through some source code to find the clipByName method and the two helper methods for finding stuff. I use this for keeping track of collage images and their bounding rectanlges ("images" and "clips"). I store them in an object:
imageObjects: {
'collage_0': http://some.tld/to/image.ext,
'collage_1': http://some.tld/to/image2.ext
}
Helper methods for finding either the clip or image:
findClipByClipName: function (clipName) {
var clip = _(canvas.getObjects()).where({ clipFor: clipName }).first();
return clip;
},
findImageByClipFor: function (clipFor) {
var image = _(canvas.getObjects()).where({ clipName: clipFor }).first();
return image;
},
Actual clipping method:
clipByName: function (ctx) {
this.setCoords();
var clipRect, scaleXTo1, scaleYTo1;
clipRect = collage.findClipByClipName(this.clipName);
scaleXTo1 = (1 / this.scaleX);
scaleYTo1 = (1 / this.scaleY);
ctx.save();
var ctxLeft, ctxTop;
ctxLeft = -(this.width / 2) + clipRect.strokeWidth;
ctxTop = -(this.height / 2) + clipRect.strokeWidth;
ctx.translate(ctxLeft, ctxTop);
ctx.rotate(degToRad(this.angle * -1));
ctx.scale(scaleXTo1, scaleYTo1);
ctx.beginPath();
ctx.rect(
clipRect.left - this.oCoords.tl.x,
clipRect.top - this.oCoords.tl.y,
clipRect.width,
clipRect.height
);
ctx.closePath();
ctx.restore();
function degToRad(degrees) {
return degrees * (Math.PI / 180);
}
},
And finally adding images to canvas where all of this comes together:
var clipName, clip, image;
clipName = helpers.findKeyByValue(url, this.imageObjects);
clip = this.findClipByClipName(clipName);
image = new Image();
image.onload = function () {
var collageImage = new fabric.Image(image, $.extend({}, collage.commonImageProps, {
left: clip.left,
top: clip.top,
clipName: clipName,
clipTo: function (ctx) {
return _.bind(collage.clipByName, collageImage)(ctx);
}
}));
collage.scaleImagesToClip(collageImage);
canvas.add(collageImage);
};

Resources