How to remove added template from canvas in fabricjs? - javascript

I need to remove added template from canvas when I insert a layout. I use following code to clear canvas but it does not work.
function clearCanvas() {
canvas.clear();
canvas.renderAll.bind(canvas);
$('#layer-list li').each(function(i,obj) {
if(!$(this).hasClass('disabled'))
$(this).remove();
});
}
Layout adding function as follows.
$(document).on('click','#layout-content .item', function(event) {
if($(this).attr('data-image')) {
var url = $(this).attr('data-image');
if(url != '') {
layoutMode = true;
clearCanvas();
loadLayout(url);
}
}
});
Loadlayout function
function loadTemplate(url) {
fabric.loadSVGFromURL(url, function(objects, options) {
var svg = fabric.util.groupSVGElements(objects,options);
svg.scaleToHeight(canvas.getHeight());
canvas.add(svg);
svg.center();
canvas.renderAll();
var bounds = svg.getObjects();
fabric.loadSVGFromURL(url, function(objects, options) {
var group = new fabric.Group(objects,options);
canvas.add(group);
group.scaleToHeight(canvas.getHeight());
canvas.renderAll();
var items = group._objects;
group._restoreObjectsState();
canvas.remove(group);
for(var i = 0; i < items.length; i++) {
var left = svg.getLeft() + bounds[i].getLeft()*svg.getScaleX();
var top = svg.getTop() + bounds[i].getTop()*svg.getScaleY();
items[i].set({
left:left,
top:top,
droppable:true,
selectable:false,
hasControls:false,
hasBorders:false,
layering:false
});
canvas.add(items[i]);
canvas.renderAll();
}
canvas.remove(svg);
makeOverlay(templateBase);//////////wrong
makeOverlay(templateText);
canvas.renderAll();
});
});
}
How to fix that issue?

There are no any problems with your function clearCanvas() and $(document).on('click','#layout-content .item', function(event). The problem is in your function loadTemplate(url).
makeOverlay(templateBase);
makeOverlay(templateText);
Above line in function loadTemplate(url) load previous base template as well. So remove those lines and try.

Related

External Javascript Libraries (cdnjs) not being reached by html code

I have been trying to add some html and javascript to my website so users can draw some shapes. I found a really good sample to work from on JS Fiddle. When I run the code on JSFiddle, it works perfectly, but when I ran it myself on my browser (I tried Edge, Firefox, and Chrome) it did not work.
When I ran it myself, I included all the scripts and css into one html file because thats the only way to add it to my Wix website. The scripts (local javascript, and external cdn libraries) where together in the body section of html. All the tutorials I found make it seem like it's OK to use the CDN libraries. I'm positive my issue has something to do with the connection to the CDN libraries, so how would I fix it?
Here is code:
var roof = null;
var roofPoints = [];
var lines = [];
var lineCounter = 0;
var drawingObject = {};
drawingObject.type = "";
drawingObject.background = "";
drawingObject.border = "";
function Point(x, y) {
this.x = x;
this.y = y;
}
$("#poly").click(function () {
if (drawingObject.type == "roof") {
drawingObject.type = "";
lines.forEach(function(value, index, ar){
canvas.remove(value);
});
//canvas.remove(lines[lineCounter - 1]);
roof = makeRoof(roofPoints);
canvas.add(roof);
canvas.renderAll();
} else {
drawingObject.type = "roof"; // roof type
}
});
// canvas Drawing
var canvas = new fabric.Canvas('canvas-tools');
var x = 0;
var y = 0;
fabric.util.addListener(window,'dblclick', function(){
drawingObject.type = "";
lines.forEach(function(value, index, ar){
canvas.remove(value);
});
//canvas.remove(lines[lineCounter - 1]);
roof = makeRoof(roofPoints);
canvas.add(roof);
canvas.renderAll();
console.log("double click");
//clear arrays
roofPoints = [];
lines = [];
lineCounter = 0;
});
canvas.on('mouse:down', function (options) {
if (drawingObject.type == "roof") {
canvas.selection = false;
setStartingPoint(options); // set x,y
roofPoints.push(new Point(x, y));
var points = [x, y, x, y];
lines.push(new fabric.Line(points, {
strokeWidth: 3,
selectable: false,
stroke: 'red'
}).setOriginX(x).setOriginY(y));
canvas.add(lines[lineCounter]);
lineCounter++;
canvas.on('mouse:up', function (options) {
canvas.selection = true;
});
}
});
canvas.on('mouse:move', function (options) {
if (lines[0] !== null && lines[0] !== undefined && drawingObject.type == "roof") {
setStartingPoint(options);
lines[lineCounter - 1].set({
x2: x,
y2: y
});
canvas.renderAll();
}
});
function setStartingPoint(options) {
var offset = $('#canvas-tools').offset();
x = options.e.pageX - offset.left;
y = options.e.pageY - offset.top;
}
function makeRoof(roofPoints) {
var left = findLeftPaddingForRoof(roofPoints);
var top = findTopPaddingForRoof(roofPoints);
roofPoints.push(new Point(roofPoints[0].x,roofPoints[0].y))
var roof = new fabric.Polyline(roofPoints, {
fill: 'rgba(0,0,0,0)',
stroke:'#58c'
});
roof.set({
left: left,
top: top,
});
return roof;
}
function findTopPaddingForRoof(roofPoints) {
var result = 999999;
for (var f = 0; f < lineCounter; f++) {
if (roofPoints[f].y < result) {
result = roofPoints[f].y;
}
}
return Math.abs(result);
}
function findLeftPaddingForRoof(roofPoints) {
var result = 999999;
for (var i = 0; i < lineCounter; i++) {
if (roofPoints[i].x < result) {
result = roofPoints[i].x;
}
}
return Math.abs(result);
}
.canvas {
border: 1px solid black;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.4.0/fabric.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<button id="poly" title="Draw Polygon" ">Draw Polygon </button>
<label style="color:blue"><b>Press double click to close shape and stop</b></label>
<canvas id="canvas-tools" class="canvas" width="500" height="500"></canvas>
EDIT
So, in the html file I put everything inside the body tag. The libraries are also included before the javascript. I get the error "Unable to get property 'x' of undefined or null reference" when I double-click to close the shape. I'm positive its because no points are added when I click in the canvas
Wix does not allow using Cloudflare. The following link has more detail.
https://support.wix.com/en/article/request-cloudflare-support
Wix has some limited API to work with HTML elements
https://support.wix.com/en/article/corvid-working-with-the-html-element
if you want to run it on a separate page (not on wix) and scripts are loaded try to wrap your javascript code in :
<script>
$(function() {
//your code here
var roof = null;
var roofPoints = [];
var lines = [];
var lineCounter = 0;
var drawingObject = {};
...
...
});
</script>

Javascript jQuery plugin - multiple instances, external control

I am trying to wrap a canvas function in a jquery plugin, so that it can be invoked via multiple instances.
I want to be able to loop through found items and call the plugin like this
http://jsfiddle.net/M99EY/69/
HTML...
<div id="select1" class="foo" data-init="multi">A</div>
<div id="select2" class="foo" data-init="multi">B</div>
<div id="select3" class="foo" data-init="multi">C</div>
<div id="select4" class="foo" data-init="multi">D</div>
JS
...
var complicatedObj = {
init: function(element){
this.el = element;
console.log("init method", this.el);
//start a complicated process
//like rendering a canvas applicaation
this.bindEvent();
this.addRandom(this.el);
},
addRandom: function(el){
$(el).text(Math.random());
},
reInit: function(){
console.log("re-initialize method");
},
bindEvent: function(){
$(this.el).click(function() {
console.log("Letter.", $(this).text());
});
}
}
//An application with complicated functions -- initialize, re-initialize
$.multiInstance = {
id: 'multiInstance',
version: '1.0',
defaults: { // default settings
foo: 'bar'
}
};
(function ($) {
//Attach this new method to jQuery
$.fn.extend({
multiInstance: function (params) {
//Merge default and user parameters
var otherGeneralVars = 'example';
return this.each(function () {
var $this = $(this), opts = $.extend({},$.multiInstance.defaults, params);
switch (params) {
case "init":
complicatedObj.init($this);
break;
case "reInit":
complicatedObj.addRandom($this);
break;
}
//console.log("$this", $this);
console.log("params", params);
//$this.text(opts.foo);
});
}
})
})(jQuery);
/*
$("#select1").multiInstance();
$("#select2").multiInstance({foo:"foobar"})
$("#select3").multiInstance("init");*/
$('[data-init="multi"]').each(function( index ) {
//console.log( index + ": " + $( this ).text());
$(this).multiInstance("init");
});
setTimeout(function(){ $('#select3').multiInstance("reInit"); }, 2000);
but I need to be able to invoke different methods, pass arguments to these methods -- and then when a change has occurred - provide a callback to catch changes to the instance
Is this the correct way of building the plugin... I want to be able to create multiple instances of the app -- but also control it externally - and also pull values out of it for external results.
This is the application I am trying to wrap into its own jquery plugin.
https://jsfiddle.net/7a4738jo/10/
css..
body {
background-color: #CCCCCC;
margin: 0;
padding: 0;
overflow: hidden;
}
canvas{
background: grey;
}
html..
<script type="text/javascript" src="https://code.createjs.com/easeljs-0.6.0.min.js"></script>
<canvas id='canvas1' data-init="canvas360" width="465" height="465"></canvas>
<canvas id='canvas2' data-init="canvas360" width="465" height="465"></canvas>
js...
var stage;
function init(element) {
var canvas = $(element)[0];
if (!canvas || !canvas.getContext) return;
stage = new createjs.Stage(canvas);
stage.enableMouseOver(true);
stage.mouseMoveOutside = true;
createjs.Touch.enable(stage);
var imgList = ["http://jsrun.it/assets/N/b/D/X/NbDXj.jpg",
"http://jsrun.it/assets/f/K/7/y/fK7yE.jpg",
"http://jsrun.it/assets/j/U/q/d/jUqdG.jpg",
"http://jsrun.it/assets/q/o/4/j/qo4jP.jpg",
"http://jsrun.it/assets/i/Q/e/1/iQe1f.jpg",
"http://jsrun.it/assets/5/k/y/R/5kyRi.jpg",
"http://jsrun.it/assets/x/T/I/h/xTIhA.jpg",
"http://jsrun.it/assets/4/X/G/F/4XGFt.jpg",
"http://jsrun.it/assets/6/7/n/r/67nrO.jpg",
"http://jsrun.it/assets/k/i/r/8/kir8T.jpg",
"http://jsrun.it/assets/2/3/F/q/23Fqt.jpg",
"http://jsrun.it/assets/c/l/d/5/cld59.jpg",
"http://jsrun.it/assets/e/J/O/f/eJOf1.jpg",
"http://jsrun.it/assets/o/j/Z/x/ojZx4.jpg",
"http://jsrun.it/assets/w/K/2/m/wK2m3.jpg",
"http://jsrun.it/assets/w/K/2/m/wK2m3.jpg",
"http://jsrun.it/assets/4/b/g/V/4bgVf.jpg",
"http://jsrun.it/assets/4/m/1/8/4m18z.jpg",
"http://jsrun.it/assets/4/w/b/F/4wbFX.jpg",
"http://jsrun.it/assets/4/k/T/G/4kTGQ.jpg",
"http://jsrun.it/assets/s/n/C/r/snCrr.jpg",
"http://jsrun.it/assets/7/f/H/u/7fHuI.jpg",
"http://jsrun.it/assets/v/S/d/F/vSdFm.jpg",
"http://jsrun.it/assets/m/g/c/S/mgcSp.jpg",
"http://jsrun.it/assets/t/L/t/P/tLtPF.jpg",
"http://jsrun.it/assets/j/7/e/H/j7eHx.jpg",
"http://jsrun.it/assets/m/o/8/I/mo8Ij.jpg",
"http://jsrun.it/assets/n/P/7/h/nP7ht.jpg",
"http://jsrun.it/assets/z/f/K/S/zfKSP.jpg",
"http://jsrun.it/assets/2/3/4/U/234U6.jpg",
"http://jsrun.it/assets/d/Z/y/m/dZymk.jpg"];
var images = [], loaded = 0, currentFrame = 0, totalFrames = imgList.length;
var rotate360Interval, start_x;
var bg = new createjs.Shape();
stage.addChild(bg);
var bmp = new createjs.Bitmap();
stage.addChild(bmp);
var myTxt = new createjs.Text("HTC One", '24px Ubuntu', "#ffffff");
myTxt.x = myTxt.y =20;
myTxt.alpha = 0.08;
stage.addChild(myTxt);
function load360Image() {
var img = new Image();
img.src = imgList[loaded];
img.onload = img360Loaded;
images[loaded] = img;
}
function img360Loaded(event) {
loaded++;
bg.graphics.clear()
bg.graphics.beginFill("#222").drawRect(0,0,stage.canvas.width * loaded/totalFrames, stage.canvas.height);
bg.graphics.endFill();
if(loaded==totalFrames) start360();
else load360Image();
}
function start360() {
document.body.style.cursor='none';
// 360 icon
var iconImage = new Image();
iconImage.src = "http://jsrun.it/assets/y/n/D/c/ynDcT.png";
iconImage.onload = iconLoaded;
// update-draw
update360(0);
// first rotation
rotate360Interval = setInterval(function(){ if(currentFrame===totalFrames-1) { clearInterval(rotate360Interval); addNavigation(); } update360(1); }, 25);
}
function iconLoaded(event) {
var iconBmp = new createjs.Bitmap();
iconBmp.image = event.target;
iconBmp.x = 20;
iconBmp.y = canvas.height - iconBmp.image.height - 20;
stage.addChild(iconBmp);
}
function update360(dir) {
currentFrame+=dir;
if(currentFrame<0) currentFrame = totalFrames-1;
else if(currentFrame>totalFrames-1) currentFrame = 0;
bmp.image = images[currentFrame];
}
//-------------------------------
function addNavigation() {
stage.onMouseOver = mouseOver;
stage.onMouseDown = mousePressed;
document.body.style.cursor='auto';
}
function mouseOver(event) {
document.body.style.cursor='pointer';
}
function mousePressed(event) {
start_x = event.rawX;
stage.onMouseMove = mouseMoved;
stage.onMouseUp = mouseUp;
document.body.style.cursor='w-resize';
}
function mouseMoved(event) {
var dx = event.rawX - start_x;
var abs_dx = Math.abs(dx);
if(abs_dx>5) {
update360(dx/abs_dx);
start_x = event.rawX;
}
}
function mouseUp(event) {
stage.onMouseMove = null;
stage.onMouseUp = null;
document.body.style.cursor='pointer';
}
function handleTick() {
stage.update();
}
document.body.style.cursor='progress';
load360Image();
// TICKER
createjs.Ticker.addEventListener("tick", handleTick);
createjs.Ticker.setFPS(60);
createjs.Ticker.useRAF = true;
}
// Init
$(document).ready(function() {
//create multiple instances of canvas
$('[data-init="canvas360"]').each(function(index) {
init(this);
});
});

Undo and redo command in canvas using fabric.js

I want to use undo and redo command in my small website, i am using fabric.js ,anybody have any idea how to do this,following is my code.on click undo & redo button i am trying to undo & redo the object of canvas This is js fiddle link
Here is fiddle link
$(document).ready(function(){
var canvas = new fabric.Canvas('c');
var colorSet="red";
$("#svg3").click(function(){
fabric.loadSVGFromURL('http://upload.wikimedia.org/wikipedia/en/c/cd/-Islandshreyfingin.svg', function (objects, options) {
var shape = fabric.util.groupSVGElements(objects, options);
shape.set({
left: canvas.width/2,
top: canvas.height/2,
scaleY: canvas.height / shape.width,
scaleX: canvas.width / shape.width
});
if (shape.isSameColor && shape.isSameColor() || !shape.paths) {
shape.setFill(colorSet);
} else if (shape.paths) {
for (var i = 0; i < shape.paths.length; i++) {
shape.paths[i].setFill(colorSet);
}
}
canvas.add(shape);
canvas.renderAll();
});
});
$("#undo").click(function(){
yourJSONString = JSON.stringify(canvas);
});
$("#redo").click(function(){
canvas.clear();
//alert(yourJSONString);
canvas.loadFromJSON(yourJSONString);
canvas.renderAll();
// alert(svgobj);
});
});
var mods = 0;
//Undo Functionality
$scope.undo = function()
{
if (mods < $scope.state.length) {
$rootScope.canvas.clear().renderAll();
$rootScope.canvas.loadFromJSON($scope.state[$scope.state.length-1 - mods - 1]);
$rootScope.canvas.renderAll();
mods += 1;
}
}
//Redo Functionality
$scope.redo = function()
{
if (mods > 0) {
$rootScope.canvas.clear().renderAll();
$rootScope.canvas.loadFromJSON($scope.state[$scope.state.length-1 - mods +
1]);
$rootScope.canvas.renderAll();
mods -= 1;
}
}
This works fine try it!!
you can write your own undo and redo function using javascript and jquery like this:
// --------------------------------undo+redu--------------------------
var vall=20;
var l=0;
var flag=0;
var k=1;
var yourJSONString = new Array();
canvas.observe('object:selected', function(e) {
//yourJSONString = JSON.stringify(canvas);
if(k!=20)
{
yourJSONString[k] = JSON.stringify(canvas);
k++;
//$('#btn').show();
}
j = k;
var activeObject = canvas.getActiveObject();
});
$("#undo").click(function(){
// counts the no of objects on canvas
var objCount = canvas.getObjects().length;
console.log("Undo"+objCount);
if(k-1 >=0)
{
canvas.clear();
canvas.loadFromJSON(yourJSONString[k-1]);
k--;
l++;
}else
{
canvas.clear();
k--;
l++;
}
canvas.renderAll();
});
$("#redo").click(function(){
// counts the no of objects on canvas
var objCount = canvas.getObjects().length;
console.log("redo"+objCount);
if(l > 1)
{
if (objCount = 0) {
canvas.clear();
canvas.loadFromJSON(yourJSONString[k-1]);
k++;
l--;
canvas.renderAll();
}
else{
canvas.clear();
canvas.loadFromJSON(yourJSONString[k+1]);
k++;
l--;
canvas.renderAll();
}
}
});
This code will perform undo and redo for every change u make on canvas. It will save the state of canvas on every change and then perform undo and redo when needed.

Return class element to default

I have 4 arrows that each one moving the piece element
now i want to create a reset button that will return the piece to the default place
//piece object
var piece = {};
piece.el = $('#piece');
piece.moveDelta = function(dx, dy){
var pos = this.el.position();
this.el.css('left', pos.left+dx);
this.el.css('top', pos.top+dy);
};
$(document).ready(function(){
//init deltas
$('#btn-up').data('dx', 0).data('dy', -100);
$('#btn-left').data('dx', -100).data('dy', 0);
$('#btn-right').data('dx', 100).data('dy', 0);
$('#btn-down').data('dx', 0).data('dy', 100);
//assign click event
$('.btn-arrow').click(function(){
piece.moveDelta($(this).data('dx'), $(this).data('dy'));
});
});
//piece object
var piece = {};
var defaultX = null;
var defaultY = null;
piece.el = $('#piece');
piece.moveDelta = function(dx, dy){
var pos = this.el.position();
if(defaultX === null && defaultY === null ){
defaultX = pos.left;
defaultY = pos.top;
}
this.el.css('left', pos.left+dx);
this.el.css('top', pos.top+dy);
};
piece.reset = function () {
this.el.css('left', defaultX);
this.el.css('top', defaultY);
};
$(document).ready(function(){
//init deltas
$('#btn-up').data('dx', 0).data('dy', -100);
$('#btn-left').data('dx', -100).data('dy', 0);
$('#btn-right').data('dx', 100).data('dy', 0);
$('#btn-down').data('dx', 0).data('dy', 100);
//assign click event
$('.btn-arrow').click(function(){
piece.moveDelta($(this).data('dx'), $(this).data('dy'));
});
$("#btn-reset").click(function(){
piece.reset();
});
});
you can use the reset method defined above. Fiddle
You can set the CSS properties to an empty string to reset them: http://jsfiddle.net/myJCq/.
piece.reset = function() {
this.el.css({ left: '', top: '' });
};

Can't create more than one overlay in Seadragon

I am trying to add overlays to a seadragon map I am making but for some reason that I can not figure our seadragon ignores all my overlays except the first one. Any help with this is much appreciated.
var viewer = null;
function init() {
Seadragon.Config.autoHideControls = false;
viewer = new Seadragon.Viewer("container");
viewer.addEventListener("open", addOverlays);
viewer.addControl(makeControl(), Seadragon.ControlAnchor.TOP_RIGHT);
$(viewer.getNavControl()).parent().parent().css({ 'top': 10, 'right': 10 });
viewer.openDzi("_assets/Mapdata/dzc_output.xml");
}
function makeControl() {
var control = document.createElement("a");
var controlText = document.createTextNode("");
control.href = "#"; // so browser shows it as link
control.className = "control";
control.appendChild(controlText);
Seadragon.Utils.addEvent(control, "click",
onControlClick);
return control;
}
function onControlClick(event) {
Seadragon.Utils.cancelEvent(event); // don't process link
if (!viewer.isOpen()) {
return;
}
// These are the coordinates of europe on this map
var x = 0.5398693914203284;
var y = 0.21155952391206562;
var z = 5;
viewer.viewport.panTo(new Seadragon.Point(x, y));
viewer.viewport.zoomTo(z);
viewer.viewport.ensureVisible();
}
function addOverlays(viewer) {
drawer = viewer.drawer;
var img = document.createElement("img");
img.src = "_assets/Images/pushpin.png";
$(img).addClass('pushPin');
var overlays = [
{ elmt: img, point: new Seadragon.Point(0.51, 0.22) },
{ elmt: img, point: new Seadragon.Point(0.20, 0.13) }
];
for (var i = 0; i < overlays.length; i++) {
drawer.addOverlay(overlays[i].elmt, overlays[i].point);
}
}
Seadragon.Utils.addEvent(window, "load", init);
I should have created a function that returns the img and call that inside the object array
function newpushPin() {
var img = document.createElement("img");
img.src = "_assets/Images/pushpin.png";
return img
}
var overlays = [
{ elmt: newpushPin(), point: new Seadragon.Point(0.51, 0.22) },
{ elmt: newpushPin(), point: new Seadragon.Point(0.53, 0.22) },
{ elmt: newpushPin(), point: new Seadragon.Point(0.53, 0.23) },
{ elmt: newpushPin(), point: new Seadragon.Point(0.50, 0.20) }
];

Categories

Resources