I have a canvas and I am loading this canvas from JSON. There are two group elements and they have their own ID (ID: 1047,1048). I keep the ID numbers to be deleted in an array of 1048,1049,1050.
var toDelete = ['1048', '1049', '1050'] ;
After JSON is loaded, if there is an item belonging to the ID in the array, I want it to be deleted. How can I do that?
According to the comparison, the ID number 1048 should be deleted.
I wrote function such code to throw incoming IDs into an array, but it didn't work.
MY PEN
function loadedIdsFunction(){ // I wrote this function to get incoming IDs but it didn't work
var loadedIds = []; //IDs of items from JSON Canvas
document.getElementById("c").fabric = canvas;
canvas.getObjects().forEach(function(o) {
if(o.type == 'group'){
loadedIds.push(o.id);
}
});
}
var canvas = new fabric.Canvas('c');
var json = '{"version":"3.1.0","objects":[{"type":"group","version":"3.1.0","originX":"left","originY":"top","left":194,"top":157,"width":40,"height":80,"fill":"rgb(0,0,0)","stroke":null,"strokeWidth":0,"strokeDashArray":null,"strokeLineCap":"butt","strokeDashOffset":0,"strokeLineJoin":"miter","strokeMiterLimit":4,"scaleX":1,"scaleY":1,"angle":0,"flipX":false,"flipY":false,"opacity":1,"shadow":null,"visible":true,"clipTo":null,"backgroundColor":"","fillRule":"nonzero","paintFirst":"fill","globalCompositeOperation":"source-over","transformMatrix":null,"skewX":0,"skewY":0,"id":"1047","objects":[{"type":"rect","version":"3.1.0","originX":"left","originY":"top","left":-20,"top":-15,"width":35,"height":50,"fill":"blue","stroke":"blue","strokeWidth":5,"strokeDashArray":null,"strokeLineCap":"butt","strokeDashOffset":0,"strokeLineJoin":"miter","strokeMiterLimit":4,"scaleX":1,"scaleY":1,"angle":0,"flipX":false,"flipY":false,"opacity":1,"shadow":null,"visible":true,"clipTo":null,"backgroundColor":"","fillRule":"nonzero","paintFirst":"fill","globalCompositeOperation":"source-over","transformMatrix":null,"skewX":0,"skewY":0,"rx":0,"ry":0,"id":"1047"},{"type":"text","version":"3.1.0","originX":"center","originY":"top","left":0,"top":-40,"width":36,"height":20.34,"fill":"red","stroke":null,"strokeWidth":1,"strokeDashArray":null,"strokeLineCap":"butt","strokeDashOffset":0,"strokeLineJoin":"miter","strokeMiterLimit":4,"scaleX":1,"scaleY":1,"angle":0,"flipX":false,"flipY":false,"opacity":1,"shadow":null,"visible":true,"clipTo":null,"backgroundColor":"white","fillRule":"nonzero","paintFirst":"fill","globalCompositeOperation":"source-over","transformMatrix":null,"skewX":0,"skewY":0,"text":"1047","fontSize":18,"fontWeight":"normal","fontFamily":"Quicksand","fontStyle":"normal","lineHeight":1.16,"underline":false,"overline":false,"linethrough":false,"textAlign":"left","textBackgroundColor":"","charSpacing":0,"styles":{}}]},{"type":"group","version":"3.1.0","originX":"left","originY":"top","left":640,"top":473,"width":40,"height":80,"fill":"rgb(0,0,0)","stroke":null,"strokeWidth":0,"strokeDashArray":null,"strokeLineCap":"butt","strokeDashOffset":0,"strokeLineJoin":"miter","strokeMiterLimit":4,"scaleX":1,"scaleY":1,"angle":0,"flipX":false,"flipY":false,"opacity":1,"shadow":null,"visible":true,"clipTo":null,"backgroundColor":"","fillRule":"nonzero","paintFirst":"fill","globalCompositeOperation":"source-over","transformMatrix":null,"skewX":0,"skewY":0,"id":"1048","objects":[{"type":"rect","version":"3.1.0","originX":"left","originY":"top","left":-20,"top":-15,"width":35,"height":50,"fill":"blue","stroke":"blue","strokeWidth":5,"strokeDashArray":null,"strokeLineCap":"butt","strokeDashOffset":0,"strokeLineJoin":"miter","strokeMiterLimit":4,"scaleX":1,"scaleY":1,"angle":0,"flipX":false,"flipY":false,"opacity":1,"shadow":null,"visible":true,"clipTo":null,"backgroundColor":"","fillRule":"nonzero","paintFirst":"fill","globalCompositeOperation":"source-over","transformMatrix":null,"skewX":0,"skewY":0,"rx":0,"ry":0,"id":"1048"},{"type":"text","version":"3.1.0","originX":"center","originY":"top","left":0,"top":-40,"width":36,"height":20.34,"fill":"red","stroke":null,"strokeWidth":1,"strokeDashArray":null,"strokeLineCap":"butt","strokeDashOffset":0,"strokeLineJoin":"miter","strokeMiterLimit":4,"scaleX":1,"scaleY":1,"angle":0,"flipX":false,"flipY":false,"opacity":1,"shadow":null,"visible":true,"clipTo":null,"backgroundColor":"white","fillRule":"nonzero","paintFirst":"fill","globalCompositeOperation":"source-over","transformMatrix":null,"skewX":0,"skewY":0,"text":"1048","fontSize":18,"fontWeight":"normal","fontFamily":"Quicksand","fontStyle":"normal","lineHeight":1.16,"underline":false,"overline":false,"linethrough":false,"textAlign":"left","textBackgroundColor":"","charSpacing":0,"styles":{}}]}],"backgroundImage":{"type":"image","version":"3.1.0","originX":"left","originY":"top","left":0,"top":0,"width":780,"height":646,"fill":"rgb(0,0,0)","stroke":null,"strokeWidth":0,"strokeDashArray":null,"strokeLineCap":"butt","strokeDashOffset":0,"strokeLineJoin":"miter","strokeMiterLimit":4,"scaleX":1,"scaleY":1,"angle":0,"flipX":false,"flipY":false,"opacity":1,"shadow":null,"visible":true,"clipTo":null,"backgroundColor":"","fillRule":"nonzero","paintFirst":"fill","globalCompositeOperation":"source-over","transformMatrix":null,"skewX":0,"skewY":0,"crossOrigin":"","cropX":0,"cropY":0,"src":"https://i1.wp.com/onideal.com/wp-content/uploads/2020/03/Schlafzimmer-Grundriss-ideale-Position-Bett-Moebel-Kleiderschrank-dreieckchen-4-780x646.jpg?fit=780%2C646&ssl=1","filters":[]}}'
canvas.loadFromJSON(json, () => canvas.renderAll(), (o, object) => {
// console.log(o, object.on);
object.on('selected', () => {
console.log(object.id);
});
});
//canvas.setBackgroundImage('https://i.hizliresim.com/iBHC0t.jpg', canvas.renderAll.bind(canvas));
//var uniqid = "0";
var uniqids = 0;
$("#door").on("click", function(e) {
rect = new fabric.Rect({
id: uniqid,
left: 40,
top: 40,
width: 35,
height: 50,
fill: 'blue',
stroke: 'blue',
strokeWidth: 5,
strokeUniform: false,
hasControls: true,
});
var uniqid = uniqids.toString();
var text = new fabric.Text(uniqid, {
fontSize: 30,
originX: 'center',
originY: 'right'
});
var group = new fabric.Group([rect, text], {
left: 0,
top: 100,
});
canvas.add(group);
uniqids++;
});
//*****************************
canvas.on('mouse:wheel', function(opt) {
var delta = opt.e.deltaY;
var zoom = canvas.getZoom();
zoom *= 0.999 ** delta;
if (zoom > 20) zoom = 20;
if (zoom < 0.01) zoom = 0.01;
canvas.setZoom(zoom);
opt.e.preventDefault();
opt.e.stopPropagation();
})
$('#getid').click(function() {
var activeObject = canvas.getActiveObjects();
alert(canvas.getActiveObject().id);
});
//***************************************
$("#save").on("click", function(e) {
$(".save").html(canvas.toSVG());
});
$('#delete').click(function() {
var activeObject = canvas.getActiveObjects();
canvas.discardActiveObject();
canvas.remove(...activeObject);
});
#c {
background-color: grey;
margin-top: 10px;
}
button {
padding: 10px 20px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/3.1.0/fabric.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<button id="door">Door</button>
<button id="delete">Delete Door</button>
<button id="save">Save</button>
<button id="getid">GET ID</button>
<p>Save bastıktan sonra altta SVG dosyası oluşur</p>
<br>
<canvas id="c" width="800" height="800"></canvas>
<br>
<p class="save">
</p>
You can filter the all the objects based on their id, if the id is in the list, remove the item. Like this:
canvas.getObjects()
.filter(obj =>
['1048', '1049', '1050'].includes(obj.id)
)
.forEach(item => canvas.remove(item));
canvas.renderAll();
var canvas = new fabric.Canvas('c');
var json = '{"version":"3.1.0","objects":[{"type":"group","version":"3.1.0","originX":"left","originY":"top","left":194,"top":157,"width":40,"height":80,"fill":"rgb(0,0,0)","stroke":null,"strokeWidth":0,"strokeDashArray":null,"strokeLineCap":"butt","strokeDashOffset":0,"strokeLineJoin":"miter","strokeMiterLimit":4,"scaleX":1,"scaleY":1,"angle":0,"flipX":false,"flipY":false,"opacity":1,"shadow":null,"visible":true,"clipTo":null,"backgroundColor":"","fillRule":"nonzero","paintFirst":"fill","globalCompositeOperation":"source-over","transformMatrix":null,"skewX":0,"skewY":0,"id":"1047","objects":[{"type":"rect","version":"3.1.0","originX":"left","originY":"top","left":-20,"top":-15,"width":35,"height":50,"fill":"blue","stroke":"blue","strokeWidth":5,"strokeDashArray":null,"strokeLineCap":"butt","strokeDashOffset":0,"strokeLineJoin":"miter","strokeMiterLimit":4,"scaleX":1,"scaleY":1,"angle":0,"flipX":false,"flipY":false,"opacity":1,"shadow":null,"visible":true,"clipTo":null,"backgroundColor":"","fillRule":"nonzero","paintFirst":"fill","globalCompositeOperation":"source-over","transformMatrix":null,"skewX":0,"skewY":0,"rx":0,"ry":0,"id":"1047"},{"type":"text","version":"3.1.0","originX":"center","originY":"top","left":0,"top":-40,"width":36,"height":20.34,"fill":"red","stroke":null,"strokeWidth":1,"strokeDashArray":null,"strokeLineCap":"butt","strokeDashOffset":0,"strokeLineJoin":"miter","strokeMiterLimit":4,"scaleX":1,"scaleY":1,"angle":0,"flipX":false,"flipY":false,"opacity":1,"shadow":null,"visible":true,"clipTo":null,"backgroundColor":"white","fillRule":"nonzero","paintFirst":"fill","globalCompositeOperation":"source-over","transformMatrix":null,"skewX":0,"skewY":0,"text":"1047","fontSize":18,"fontWeight":"normal","fontFamily":"Quicksand","fontStyle":"normal","lineHeight":1.16,"underline":false,"overline":false,"linethrough":false,"textAlign":"left","textBackgroundColor":"","charSpacing":0,"styles":{}}]},{"type":"group","version":"3.1.0","originX":"left","originY":"top","left":640,"top":473,"width":40,"height":80,"fill":"rgb(0,0,0)","stroke":null,"strokeWidth":0,"strokeDashArray":null,"strokeLineCap":"butt","strokeDashOffset":0,"strokeLineJoin":"miter","strokeMiterLimit":4,"scaleX":1,"scaleY":1,"angle":0,"flipX":false,"flipY":false,"opacity":1,"shadow":null,"visible":true,"clipTo":null,"backgroundColor":"","fillRule":"nonzero","paintFirst":"fill","globalCompositeOperation":"source-over","transformMatrix":null,"skewX":0,"skewY":0,"id":"1048","objects":[{"type":"rect","version":"3.1.0","originX":"left","originY":"top","left":-20,"top":-15,"width":35,"height":50,"fill":"blue","stroke":"blue","strokeWidth":5,"strokeDashArray":null,"strokeLineCap":"butt","strokeDashOffset":0,"strokeLineJoin":"miter","strokeMiterLimit":4,"scaleX":1,"scaleY":1,"angle":0,"flipX":false,"flipY":false,"opacity":1,"shadow":null,"visible":true,"clipTo":null,"backgroundColor":"","fillRule":"nonzero","paintFirst":"fill","globalCompositeOperation":"source-over","transformMatrix":null,"skewX":0,"skewY":0,"rx":0,"ry":0,"id":"1048"},{"type":"text","version":"3.1.0","originX":"center","originY":"top","left":0,"top":-40,"width":36,"height":20.34,"fill":"red","stroke":null,"strokeWidth":1,"strokeDashArray":null,"strokeLineCap":"butt","strokeDashOffset":0,"strokeLineJoin":"miter","strokeMiterLimit":4,"scaleX":1,"scaleY":1,"angle":0,"flipX":false,"flipY":false,"opacity":1,"shadow":null,"visible":true,"clipTo":null,"backgroundColor":"white","fillRule":"nonzero","paintFirst":"fill","globalCompositeOperation":"source-over","transformMatrix":null,"skewX":0,"skewY":0,"text":"1048","fontSize":18,"fontWeight":"normal","fontFamily":"Quicksand","fontStyle":"normal","lineHeight":1.16,"underline":false,"overline":false,"linethrough":false,"textAlign":"left","textBackgroundColor":"","charSpacing":0,"styles":{}}]}],"backgroundImage":{"type":"image","version":"3.1.0","originX":"left","originY":"top","left":0,"top":0,"width":780,"height":646,"fill":"rgb(0,0,0)","stroke":null,"strokeWidth":0,"strokeDashArray":null,"strokeLineCap":"butt","strokeDashOffset":0,"strokeLineJoin":"miter","strokeMiterLimit":4,"scaleX":1,"scaleY":1,"angle":0,"flipX":false,"flipY":false,"opacity":1,"shadow":null,"visible":true,"clipTo":null,"backgroundColor":"","fillRule":"nonzero","paintFirst":"fill","globalCompositeOperation":"source-over","transformMatrix":null,"skewX":0,"skewY":0,"crossOrigin":"","cropX":0,"cropY":0,"src":"https://i1.wp.com/onideal.com/wp-content/uploads/2020/03/Schlafzimmer-Grundriss-ideale-Position-Bett-Moebel-Kleiderschrank-dreieckchen-4-780x646.jpg?fit=780%2C646&ssl=1","filters":[]}}'
canvas.loadFromJSON(json, () => {
canvas.getObjects()
.filter(obj => ['1048', '1049', '1050'].includes(obj.id))
.forEach(item => canvas.remove(item));
canvas.renderAll();
}, (o, object) => {
// console.log(o, object.on);
object.on('selected', () => {
console.log(object.id);
});
});
//canvas.setBackgroundImage('https://i.hizliresim.com/iBHC0t.jpg', canvas.renderAll.bind(canvas));
//var uniqid = "0";
var uniqids = 0;
$("#door").on("click", function(e) {
rect = new fabric.Rect({
id: uniqid,
left: 40,
top: 40,
width: 35,
height: 50,
fill: 'blue',
stroke: 'blue',
strokeWidth: 5,
strokeUniform: false,
hasControls: true,
});
var uniqid = uniqids.toString();
var text = new fabric.Text(uniqid, {
fontSize: 30,
originX: 'center',
originY: 'right'
});
var group = new fabric.Group([rect, text], {
left: 0,
top: 100,
});
canvas.add(group);
uniqids++;
});
//*****************************
canvas.on('mouse:wheel', function(opt) {
var delta = opt.e.deltaY;
var zoom = canvas.getZoom();
zoom *= 0.999 ** delta;
if (zoom > 20) zoom = 20;
if (zoom < 0.01) zoom = 0.01;
canvas.setZoom(zoom);
opt.e.preventDefault();
opt.e.stopPropagation();
})
$('#getid').click(function() {
var activeObject = canvas.getActiveObjects();
alert(canvas.getActiveObject().id);
});
//***************************************
$("#save").on("click", function(e) {
$(".save").html(canvas.toSVG());
});
$('#delete').click(function() {
var activeObject = canvas.getActiveObjects();
canvas.discardActiveObject();
canvas.remove(...activeObject);
});
/*
canvas.on('mouse:over', function(e) {
e.target.set('fill', 'red');
canvas.renderAll();
});
canvas.on('mouse:out', function(e) {
e.target.set('fill', 'green');
canvas.renderAll();
});
*/
#c {
background-color: grey;
margin-top: 10px;
}
button {
padding: 10px 20px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/3.1.0/fabric.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<button id="door">Door</button>
<button id="delete">Delete Door</button>
<button id="save">Save</button>
<button id="getid">GET ID</button>
<p>Save bastıktan sonra altta SVG dosyası oluşur</p>
<br>
<canvas id="c" width="800" height="800"></canvas>
<br>
<p class="save">
</p>
https://codepen.io/moshfeu/pen/gOMBQqL?editors=0010
Note: I have refereed SO question, but it is not useful for my case, because
1) I am trying to maintain previous border but as of now its recalculate border while scaling.
I have added below code to stop increasing border automatically while scaling the object. Now the issue is I have added a 5px border to object but when scaling the object then it is not maintaining the border which I added earlier.
canvas.on('object:scaling', (e) => {
var o = e.target;
if (!o.strokeWidthUnscaled && o.strokeWidth) {
o.strokeWidthUnscaled = o.strokeWidth;
}
if (o.strokeWidthUnscaled) {
o.strokeWidth = o.strokeWidthUnscaled / o.scaleX;
}
});
Now what I want is to prevent increasing of border while scaling the object. Border should remain as it was earlier.
Here is snippet / Codepen
var canvas = new fabric.Canvas('canvas1');
$('.add_shape').click(function() {
var cur_value = $(this).attr('data-rel');
if (cur_value != '') {
switch (cur_value) {
case 'rectangle':
var rect = new fabric.Rect({
left: 50,
top: 50,
fill: '#aaa',
width: 50,
height: 50,
opacity: 1,
stroke: '#000',
strokeWidth: 1
});
canvas.add(rect);
canvas.setActiveObject(rect);
break;
case 'circle':
var circle = new fabric.Circle({
left: 50,
top: 50,
fill: '#aaa',
radius: 50,
opacity: 1,
stroke: '#000',
strokeWidth: 1
});
canvas.add(circle);
canvas.setActiveObject(circle);
break;
}
}
});
canvas.on('object:scaling', (e) => {
var o = e.target;
if (!o.strokeWidthUnscaled && o.strokeWidth) {
o.strokeWidthUnscaled = o.strokeWidth;
}
if (o.strokeWidthUnscaled) {
o.strokeWidth = o.strokeWidthUnscaled / o.scaleX;
}
});
/* Control the border */
$('#control_border').change(function() {
var cur_value = parseInt($(this).val());
var activeObj = canvas.getActiveObject();
if (activeObj == undefined) {
alert('Please select the Object');
return false;
}
activeObj.set({
strokeWidth: cur_value
});
canvas.renderAll();
});
button {
max-resolution: 10px;
height: 30px;
}
div {
margin: 10px
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/2.0.0-beta.7/fabric.js"></script>
<div>
<button class="add_shape" data-rel="circle">Add Circle</button>
<button class="add_shape" data-rel="rectangle">Add Rectangle</button>
<label class="control-label">Border</label>
<input id="control_border" type="range" min="0" max="10" step="1" value="0" />
</div>
<canvas id="canvas1" width="600" height="300" style="border:1px solid #000000;"></canvas>
Steps
1) Add Rectangle
2) Apply the border (lets say 5)
3) Scale that object
Now you can see the applied border is gone. So how to resolve that?
Update
I have tried below option but its not working, basically i am trying to maintain strokeWidth/Border for objects like rectangle, circle, triangle, line, polygon
What i have tried so far:
//1st try
canvas.on('object:scaling', (e) => {
var o = e.target;
o.strokeWidth = o.strokeWidth / ((o.scaleX + o.scaleY) / 2);
var activeObject = canvas.getActiveObject();
activeObject.set('strokeWidth',o.strokeWidth);
});
//2nd try
canvas.on('object:scaling', (e) => {
if (!o.strokeWidthUnscaled && o.strokeWidth) {
o.strokeWidthUnscaled = o.strokeWidth;
}
if (o.strokeWidthUnscaled) {
o.strokeWidth = o.strokeWidthUnscaled / o.scaleX;
}
});
//3rd try
fabric.Object.prototype._renderStroke = function(ctx) {
if (!this.stroke || this.strokeWidth === 0) {
return;
}
if (this.shadow && !this.shadow.affectStroke) {
this._removeShadow(ctx);
}
ctx.save();
ctx.scale(1 / this.scaleX, 1 / this.scaleY);
this._setLineDash(ctx, this.strokeDashArray, this._renderDashedStroke);
this._applyPatternGradientTransform(ctx, this.stroke);
ctx.stroke();
ctx.restore();
};
Questions i have refereed:
https://github.com/kangax/fabric.js/issues/66
Unable to maintain thickness of strokeWidth while resizing in case of Groups in Fabricjs
Fabricjs How to scale object but keep the border (stroke) width fixed
Resize a fabricjs rect to maintain border size
https://github.com/kangax/fabric.js/issues/2012
But not able to found solution.
This has become much easier as of Fabric.js version 2.7.0. There is now a strokeUniform property that when enabled, prevents the stroke width from being affected by the object's scale values.
obj.set('strokeUniform', true);
https://github.com/fabricjs/fabric.js/pull/5546
var canvas = new fabric.Canvas('canvas1');
$('.add_shape').click(function() {
var cur_value = $(this).attr('data-rel');
if (cur_value != '') {
switch (cur_value) {
case 'rectangle':
var rect = new fabric.Rect({
left: 50,
top: 50,
fill: '#aaa',
width: 50,
height: 50,
opacity: 1,
stroke: '#000',
strokeWidth: 1,
noScaleCache: false,
strokeUniform: true,
});
canvas.add(rect);
canvas.setActiveObject(rect);
break;
case 'circle':
var circle = new fabric.Circle({
left: 50,
top: 50,
fill: '#aaa',
radius: 50,
opacity: 1,
stroke: '#000',
strokeWidth: 1,
noScaleCache: false,
strokeUniform: true
});
canvas.add(circle);
canvas.setActiveObject(circle);
break;
}
}
});
/* Control the border */
$('#control_border').change(function() {
var cur_value = parseInt($(this).val());
var activeObj = canvas.getActiveObject();
if (activeObj == undefined) {
alert('Please select the Object');
return false;
}
activeObj.set({
strokeWidth: cur_value
});
canvas.renderAll();
});
button {
max-resolution: 10px;
height: 30px;
}
div {
margin: 10px
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/2.7.0/fabric.min.js"></script>
<div>
<button class="add_shape" data-rel="circle">Add Circle</button>
<button class="add_shape" data-rel="rectangle">Add Rectangle</button>
<label class="control-label">Border</label>
<input id="control_border" type="range" min="0" max="10" step="1" value="0" />
</div>
<canvas id="canvas1" width="600" height="300" style="border:1px solid #000000;"></canvas>
Set strokeWidth to strokeWidthUnscaled for first time then set # at scalling, for caching make it false only when scalling after modified change it.
object.strokeWidth = object.strokeWidthUnscaled/((object.scaleX+object.scaleY)/2);
And for selecting new stroke width, do this
var newStrokeWidth = cur_value / ((activeObj.scaleX + activeObj.scaleY) / 2)
activeObj.set({
strokeWidth: newStrokeWidth,
strokeWidthUnscaled : cur_value
});
Example
var canvas = new fabric.Canvas('canvas1');
var globalStrokeWidth = 1;
$('.add_shape').click(function() {
var cur_value = $(this).attr('data-rel');
if (cur_value != '') {
switch (cur_value) {
case 'rectangle':
var rect = new fabric.Rect({
left: 50,
top: 50,
fill: '#aaa',
width: 50,
height: 50,
opacity: 1,
stroke: '#000',
strokeWidth: globalStrokeWidth
});
canvas.add(rect);
canvas.setActiveObject(rect);
break;
case 'circle':
var circle = new fabric.Circle({
left: 50,
top: 50,
fill: '#aaa',
radius: 50,
opacity: 1,
stroke: '#000',
strokeWidth: globalStrokeWidth
});
canvas.add(circle);
canvas.setActiveObject(circle);
break;
}
}
});
canvas.on('object:scaling', (e) => {
var o = e.target;
if (!o.strokeWidthUnscaled && o.strokeWidth) {
o.strokeWidthUnscaled = o.strokeWidth;
}
if (o.strokeWidthUnscaled) {
if(o.objectCaching) o.objectCaching = false;
o.strokeWidth = o.strokeWidthUnscaled / ((o.scaleX + o.scaleY) / 2);
}
});
canvas.on('object:modified', (e) => {
var o = e.target;
if(!o.objectCaching) o.objectCaching = true;
canvas.renderAll();
});
/* Control the border */
$('#control_border').change(function() {
var cur_value = parseInt($(this).val());
globalStrokeWidth = cur_value;
var activeObj = canvas.getActiveObject();
if (activeObj == undefined) {
alert('Please select the Object');
return false;
}
var newStrokeWidth = cur_value / ((activeObj.scaleX + activeObj.scaleY) / 2)
activeObj.set({
strokeWidth: newStrokeWidth,
strokeWidthUnscaled : cur_value
});
activeObj.setCoords();
canvas.renderAll();
});
button {
max-resolution: 10px;
height: 30px;
}
div {
margin: 10px
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/2.0.0-beta.7/fabric.js"></script>
<div>
<button class="add_shape" data-rel="circle">Add Circle</button>
<button class="add_shape" data-rel="rectangle">Add Rectangle</button>
<label class="control-label">Border</label>
<input id="control_border" type="range" min="0" max="10" step="1" value="0" />
</div>
<canvas id="canvas1" width="600" height="300" style="border:1px solid #000000;"></canvas>
While working on this issue, I've noticed that after resizing an object value of width and height doesn't change, it only changes scaleX and scaleY.
To maintain the stroke width, you need to reset scaleX and scalyY to 1 and also update width and height with new values.
For rectangle:
var currObj = canvas.getActiveObject();
if (currObj.type === 'rect') {
var newWidth = currObj.width * currObj.scaleX,
newHeight = currObj.height * currObj.scaleY;
currObj.set({
'width': newWidth,
'height': newHeight,
scaleX: 1,
scaleY: 1
});
}
For Ellipse:
var currObj = canvas.getActiveObject();
if (currObj.type === 'ellipse') {
var newRX = currObj.rx * currObj.scaleX,
newRY = currObj.ry * currObj.scaleY;
currObj.set({
'rx': newRX,
'ry': newRY,
scaleX: 1,
scaleY: 1
});
}
Don't forget to call canvas.renderAll() later;
http://jsfiddle.net/eLoamgrq/5/
In object:scaling, I commented out the calculation based on scale. Since the unscaled was = 1 and it was divided by scaling it always resulted in the border equaling a fraction (rather than staying put).
var canvas = new fabric.Canvas('canvas1');
$('.add_shape').click(function() {
var cur_value = $(this).attr('data-rel');
if (cur_value != '') {
switch (cur_value) {
case 'rectangle':
var rect = new fabric.Rect({
left: 50,
top: 50,
fill: '#aaa',
width: 50,
height: 50,
opacity: 1,
stroke: '#000',
strokeWidth: 1
});
canvas.add(rect);
canvas.setActiveObject(rect);
break;
case 'circle':
var circle = new fabric.Circle({
left: 50,
top: 50,
fill: '#aaa',
radius: 50,
opacity: 1,
stroke: '#000',
strokeWidth: 1
});
canvas.add(circle);
canvas.setActiveObject(circle);
break;
}
}
});
canvas.on('object:scaling', (e) => {
var o = e.target;
if (!o.strokeWidthUnscaled && o.strokeWidth) {
o.strokeWidthUnscaled = o.strokeWidth;
}
if (o.strokeWidthUnscaled) {
//o.strokeWidth = o.strokeWidthUnscaled / o.scaleX;
}
});
/* Control the border */
$('#control_border').change(function() {
var cur_value = parseInt($(this).val());
var activeObj = canvas.getActiveObject();
if (activeObj == undefined) {
alert('Please select the Object');
return false;
}
activeObj.set({
strokeWidth: cur_value
});
canvas.renderAll();
});
button {
max-resolution: 10px;
height: 30px;
}
div {
margin: 10px
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/2.0.0-beta.7/fabric.js"></script>
<div>
<button class="add_shape" data-rel="circle">Add Circle</button>
<button class="add_shape" data-rel="rectangle">Add Rectangle</button>
<label class="control-label">Border</label>
<input id="control_border" type="range" min="0" max="10" step="1" value="0" />
</div>
<canvas id="canvas1" width="600" height="300" style="border:1px solid #000000;"></canvas>
If your object is inside a group, strokeUniform property does not work. In that case you can reduce the scaling of the inner object and update its width and height property on scaling. Example:
object.on('scaling', function() {
object.item(0).set('scaleX', 1/object.scaleX);
object.item(0).set('scaleY', 1/object.scaleY);
var newobjwidth = Math.round(object.width * object.scaleX);
var newobjheight = Math.round(object.height * object.scaleY);
object.item(0).set('width', newobjwidth);
object.item(0).set('height', newobjheight);
object.item(0).setCoords();
}
If your object is blurry delete it and add it again after scaling.
I want to be able to upload images onto this canvas from the persons computer just for the time being while they use the canvas. I also want it to be moveable and resizeable like the other 2 images I have setup right now. Can someone help create a code that goes along with what I currently have. This is everything I have for it so far so if you could name such with the right class/ids that the parts of mine have. Thank you
<style>
canvas:active{
cursor:pointer;
}
.bg1{
background-image:url('http://s23.postimg.org/bxtmsd2tn/boutiquebase.jpg');
}
.bg2{
background-image:url('http://s4.postimg.org/bnevxi1y5/wall8.png');
}
.bg3{
background-image:url('http://s13.postimg.org/6cgbaoblh/wall9.png');
}
</style>
<div id="container" class="bg1"></div>
<img src="http://s23.postimg.org/bxtmsd2tn/boutiquebase.jpg" width="50px" id="wall1">
<img src="http://s4.postimg.org/bnevxi1y5/wall8.png" width="50px" id="wall2">
<img src="http://s13.postimg.org/6cgbaoblh/wall9.png" width="50px" id="wall3">
<table><tr>
<td>
<center> <img src="http://s29.postimg.org/yn6t21ah3/sidetable.png" id="shower" width="100px" style="cursor:pointer;">
<br>
<span id="hider1" class="sendingBut" style="cursor:pointer;">Remove </span>
</center></td>
</tr>
</table>
<script src="http://d3lp1msu2r81bx.cloudfront.net/kjs/js/lib/kinetic-v5.0.2.min.js"></script>
<script>
$('#wall2').click(function() {
$('#container').removeClass('bg3').removeClass('bg1').addClass('bg2');
});
$('#wall1').click(function() {
$('#container').removeClass('bg3').removeClass('bg2').addClass('bg1');
});
$('#wall3').click(function() {
$('#container').removeClass('bg1').removeClass('bg2').addClass('bg3');
});
</script>
<script>
function update(activeAnchor) {
var group = activeAnchor.getParent();
var topLeft = group.find('.topLeft')[0];
var topRight = group.find('.topRight')[0];
var bottomRight = group.find('.bottomRight')[0];
var bottomLeft = group.find('.bottomLeft')[0];
var image = group.find('.image')[0];
var anchorX = activeAnchor.x();
var anchorY = activeAnchor.y();
// update anchor positions
switch (activeAnchor.name()) {
case 'topLeft':
topRight.y(anchorY);
bottomLeft.x(anchorX);
break;
case 'topRight':
topLeft.y(anchorY);
bottomRight.x(anchorX);
break;
case 'bottomRight':
bottomLeft.y(anchorY);
topRight.x(anchorX);
break;
case 'bottomLeft':
bottomRight.y(anchorY);
topLeft.x(anchorX);
break;
}
image.setPosition(topLeft.getPosition());
var width = topRight.x() - topLeft.x();
var height = bottomLeft.y() - topLeft.y();
if(width && height) {
image.setSize({width:width, height: height});
}
}
function addAnchor(group, x, y, name) {
var stage = group.getStage();
var layer = group.getLayer();
var anchor = new Kinetic.Circle({
x: x,
y: y,
stroke: '#666',
fill: '#ddd',
strokeWidth: 2,
radius: 8,
name: name,
draggable: true,
dragOnTop: false,
opacity: .01
});
anchor.on('mouseout', function () {
this.opacity(.01);
layer.draw()
});
anchor.on('mouseenter', function () {
this.opacity(1.00);
layer.draw()
});
anchor.on('dragmove', function() {
update(this);
layer.draw();
});
anchor.on('mousedown touchstart', function() {
group.setDraggable(false);
this.moveToTop();
});
anchor.on('dragend', function() {
group.setDraggable(true);
layer.draw();
});
// add hover styling
anchor.on('mouseover', function() {
var layer = this.getLayer();
document.body.style.cursor = 'pointer';
this.setStrokeWidth(4);
layer.draw();
});
anchor.on('mouseout', function() {
var layer = this.getLayer();
document.body.style.cursor = 'default';
this.strokeWidth(2);
layer.draw();
});
group.add(anchor);
}
function loadImages(sources, callback) {
var images = {};
var loadedImages = 0;
var numImages = 0;
for(var src in sources) {
numImages++;
}
for(var src in sources) {
images[src] = new Image();
images[src].onload = function() {
if(++loadedImages >= numImages) {
callback(images);
}
};
images[src].src = sources[src];
}
}
function initStage(images) {
var stage = new Kinetic.Stage({
container: 'container',
width: 1000,
height: 764
});
var layer = new Kinetic.Layer();
var furniGroup = new Kinetic.Group({
x: 270,
y: 100,
draggable: true
});
var yodaGroup = new Kinetic.Group({
x: 100,
y: 110,
draggable: true
});
/*
* go ahead and add the groups
* to the layer and the layer to the
* stage so that the groups have knowledge
* of its layer and stage
*/
layer.add(furniGroup);
layer.add(yodaGroup);
stage.add(layer);
document.getElementById('shower').addEventListener('click', function() {
furniImg.show();
layer.draw();
}, false);
document.getElementById('hider1').addEventListener('click', function() {
furniImg.hide();
layer.draw();
}, false);
var furniImg = new Kinetic.Image({
x: 0,
y: 0,
width: 338,
height: 285,
image: images.furni,
name: 'image'
});
furniGroup.add(furniImg);
addAnchor(furniGroup, 0, 0, 'topLeft');
addAnchor(furniGroup, 338, 0, 'topRight');
addAnchor(furniGroup, 338, 285, 'bottomRight');
addAnchor(furniGroup, 0, 285, 'bottomLeft');
furniGroup.on('dragstart', function() {
this.moveToTop();
});
var yodaImg = new Kinetic.Image({
x: 0,
y: 0,
image: images.yoda,
width: 422,
height: 243,
name: 'image'
});
yodaGroup.add(yodaImg);
addAnchor(yodaGroup, 0, 0, 'topLeft');
addAnchor(yodaGroup, 422, 0, 'topRight');
addAnchor(yodaGroup, 422, 243, 'bottomRight');
addAnchor(yodaGroup, 0, 243, 'bottomLeft');
yodaGroup.on('dragstart', function() {
this.moveToTop();
});
stage.draw();
}
var sources = {
furni: 'http://s29.postimg.org/yn6t21ah3/sidetable.png',
yoda: 'http://s28.postimg.org/58nni8dzh/blackf10.png'
};
loadImages(sources, initStage);
</script>
This code lets you drag an image from the users desktop onto the Kinetic container div.
A new Kinetic.Image will be created from the dropped image.
Example code and a Demo: http://jsfiddle.net/m1erickson/w9onv0nm/
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Prototype</title>
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<script src="http://d3lp1msu2r81bx.cloudfront.net/kjs/js/lib/kinetic-v5.1.0.min.js"></script>
<style>
body{ background-color: ivory; }
canvas{border:1px solid red;}
body{padding:20px;}
#container{
border:solid 1px #ccc;
margin-top: 10px;
width:350px;
height:350px;
}
</style>
<script>
$(function(){
var stage = new Kinetic.Stage({
container: 'container',
width: 350,
height: 350
});
var layer = new Kinetic.Layer();
stage.add(layer);
// drag image to the div with id='container'
var container=document.getElementById("container");
container.addEventListener("dragover", function(e){ e.preventDefault(); }, false);
container.addEventListener("drop", function(e){
var files = e.dataTransfer.files;
if (files.length>0) {
var file=files[0];
if (typeof FileReader !== "undefined" && file.type.indexOf("image") != -1) {
var reader=new FileReader();
reader.onload=function (e) {
var dragImage=new Image();
dragImage.onload=function(){
newDraggedImage(dragImage);
};
dragImage.src=e.target.result;
};
reader.readAsDataURL(file);
}
}
e.preventDefault();
}, false);
// create a new Kinetic.Image from the dropped image
function newDraggedImage(img){
layer.add(new Kinetic.Image({
image:img,
draggable:true,
}));
layer.draw();
}
}); // end $(function(){});
</script>
</head>
<body>
<h4>Drag an image onto the container to create a Kinetic.Image</h4>
<div id="container"></div><br>
</body>
</html>
[ Addition - creating group & anchors for dropped images ]
Warning! This is untested code...tweaking is probably required!
function createGroup(groupId,img,x,y){
var group = new Kinetic.Group({
id:groupId,
x:x,
y:y,
draggable: true
});
layer.add(group);
var image = new Kinetic.Image({
x: 0,
y: 0,
image:img,
width:img.width,
height:img.height,
name: 'image'
});
group.add(image);
addAnchor(group, 0, 0, 'topLeft');
addAnchor(group, img.width, 0, 'topRight');
addAnchor(group, img.width, img.height, 'bottomRight');
addAnchor(group, 0, img.height, 'bottomLeft');
group.on('dragstart', function() {
this.moveToTop();
});
return(group);
}