How to identify fabric js image objects inserted to canvas? - javascript

In here there are two images with two different id's.Is there a way to identify the image which are inserted(drag and drop) images to the canvas.(I want to get the id's images that are inserted to the canvas).
I'm trying to sent image details(x,y, width,height) to the database with unique image id. Is there a way to this in fabric js.
function initCanvas() {
$('.canvas-container').each(function(index) {
var canvasContainer = $(this)[0];
var canvasObject = $("canvas", this)[0];
var imageOffsetX, imageOffsetY;
function handleDragStart(e) {
[].forEach.call(images, function(img) {
img.classList.remove('img_dragging');
});
this.classList.add('img_dragging');
var imageOffset = $(this).offset();
imageOffsetX = e.clientX - imageOffset.left;
imageOffsetY = e.clientY - imageOffset.top;
}
function handleDragOver(e) {
if (e.preventDefault) {
e.preventDefault();
}
e.dataTransfer.dropEffect = 'copy';
return false;
}
function handleDragEnter(e) {
this.classList.add('over');
}
function handleDragLeave(e) {
this.classList.remove('over');
}
function handleDrop(e) {
e = e || window.event;
if (e.preventDefault) {
e.preventDefault();
}
if (e.stopPropagation) {
e.stopPropagation();
}
var img = document.querySelector('.furniture img.img_dragging');
console.log('event: ', e);
var offset = $(canvasObject).offset();
var y = e.clientY - (offset.top + imageOffsetY);
var x = e.clientX - (offset.left + imageOffsetX);
var newImage = new fabric.Image(img, {
width: img.width,
height: img.height,
left: x,
top: y
});
canvas.add(newImage);
return false;
}
function handleDragEnd(e) {
[].forEach.call(images, function(img) {
img.classList.remove('img_dragging');
});
}
var images = document.querySelectorAll('.furniture img');
[].forEach.call(images, function(img) {
img.addEventListener('dragstart', handleDragStart, false);
img.addEventListener('dragend', handleDragEnd, false);
});
canvasContainer.addEventListener('dragenter', handleDragEnter, false);
canvasContainer.addEventListener('dragover', handleDragOver, false);
canvasContainer.addEventListener('dragleave', handleDragLeave, false);
canvasContainer.addEventListener('drop', handleDrop, false);
});
}
initCanvas();
var canvas = new fabric.Canvas('canvas1', {
selection: false
});
<div class="fullpage">
<div class="section">
<div class="canvas-container">
<canvas id="canvas1" style="border: 1px solid;width: 500px;height: 500px"></canvas>
</div>
<div class="furniture" style="padding: 20px;border: 1px solid;width: 460px">
<h3>Drag the image to canvas</h3>
<img id="pic1" draggable="true" src="https://www.mve.com/media/Move_logo_-01.png" width="60">
<img id="pic2" draggable="true" src="https://young.scot/media/8787/second-chances-logo-802x644.png" width="60">
</div>
</div>
</div>
<script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js'></script>
<script src='https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.7.6/fabric.min.js'></script>

You can get the id from dragged element, and add as a proerty of image object.
function initCanvas() {
$('.canvas-container').each(function(index) {
var canvasContainer = $(this)[0];
var canvasObject = $("canvas", this)[0];
var imageOffsetX, imageOffsetY;
function handleDragStart(e) {
[].forEach.call(images, function(img) {
img.classList.remove('img_dragging');
});
this.classList.add('img_dragging');
var imageOffset = $(this).offset();
imageOffsetX = e.clientX - imageOffset.left;
imageOffsetY = e.clientY - imageOffset.top;
}
function handleDragOver(e) {
if (e.preventDefault) {
e.preventDefault();
}
e.dataTransfer.dropEffect = 'copy';
return false;
}
function handleDragEnter(e) {
this.classList.add('over');
}
function handleDragLeave(e) {
this.classList.remove('over');
}
function handleDrop(e) {
e = e || window.event;
if (e.preventDefault) {
e.preventDefault();
}
if (e.stopPropagation) {
e.stopPropagation();
}
var img = document.querySelector('.furniture img.img_dragging');
//console.log('event: ', e);
var offset = $(canvasObject).offset();
var y = e.clientY - (offset.top + imageOffsetY);
var x = e.clientX - (offset.left + imageOffsetX);
var newImage = new fabric.Image(img, {
width: img.width,
height: img.height,
left: x,
top: y,
id: img.id
});
canvas.add(newImage);
console.log(newImage.id)
return false;
}
function handleDragEnd(e) {
[].forEach.call(images, function(img) {
img.classList.remove('img_dragging');
});
}
var images = document.querySelectorAll('.furniture img');
[].forEach.call(images, function(img) {
img.addEventListener('dragstart', handleDragStart, false);
img.addEventListener('dragend', handleDragEnd, false);
});
canvasContainer.addEventListener('dragenter', handleDragEnter, false);
canvasContainer.addEventListener('dragover', handleDragOver, false);
canvasContainer.addEventListener('dragleave', handleDragLeave, false);
canvasContainer.addEventListener('drop', handleDrop, false);
});
}
initCanvas();
var canvas = new fabric.Canvas('canvas1', {
selection: false
});
<div class="fullpage">
<div class="section">
<div class="canvas-container">
<canvas id="canvas1" style="border: 1px solid;width: 500px;height: 500px"></canvas>
</div>
<div class="furniture" style="padding: 20px;border: 1px solid;width: 460px">
<h3>Drag the image to canvas</h3>
<img id="pic1" draggable="true" src="https://www.mve.com/media/Move_logo_-01.png" width="60">
<img id="pic2" draggable="true" src="https://young.scot/media/8787/second-chances-logo-802x644.png" width="60">
</div>
</div>
</div>
<script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js'></script>
<script src='https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.7.6/fabric.min.js'></script>

Use canvas.on('object:modified') function or get active object and perform your action on it
function initCanvas() {
$('.canvas-container').each(function(index) {
var canvasContainer = $(this)[0];
var canvasObject = $("canvas", this)[0];
var imageOffsetX, imageOffsetY;
function handleDragStart(e) {
[].forEach.call(images, function(img) {
img.classList.remove('img_dragging');
});
this.classList.add('img_dragging');
var imageOffset = $(this).offset();
imageOffsetX = e.clientX - imageOffset.left;
imageOffsetY = e.clientY - imageOffset.top;
}
function handleDragOver(e) {
if (e.preventDefault) {
e.preventDefault();
}
e.dataTransfer.dropEffect = 'copy';
return false;
}
function handleDragEnter(e) {
this.classList.add('over');
}
function handleDragLeave(e) {
this.classList.remove('over');
}
function handleDrop(e) {
e = e || window.event;
if (e.preventDefault) {
e.preventDefault();
}
if (e.stopPropagation) {
e.stopPropagation();
}
var img = document.querySelector('.furniture img.img_dragging');
console.log('event: ', e);
var offset = $(canvasObject).offset();
var y = e.clientY - (offset.top + imageOffsetY);
var x = e.clientX - (offset.left + imageOffsetX);
var newImage = new fabric.Image(img, {
width: img.width,
height: img.height,
left: x,
top: y,
id:'SomeID'
//Object id for identify
});
canvas.add(newImage);
return false;
}
function handleDragEnd(e) {
[].forEach.call(images, function(img) {
img.classList.remove('img_dragging');
});
}
var images = document.querySelectorAll('.furniture img');
[].forEach.call(images, function(img) {
img.addEventListener('dragstart', handleDragStart, false);
img.addEventListener('dragend', handleDragEnd, false);
});
canvasContainer.addEventListener('dragenter', handleDragEnter, false);
canvasContainer.addEventListener('dragover', handleDragOver, false);
canvasContainer.addEventListener('dragleave', handleDragLeave, false);
canvasContainer.addEventListener('drop', handleDrop, false);
});
}
initCanvas();
var canvas = new fabric.Canvas('canvas1', {
selection: false
});
canvas.on('object:modified', function (e) {
var activeobject = e.target;
//Do as need
console.log(activeobject);
alert(activeobject.get('id'));
});

Related

Why image is not changing on button click?

Could you please tell me why my image is not change on button click here is my code
http://plnkr.co/edit/zQPp1vya27a5UaCJmbE7?p=preview
<button ng-click="clik()">chnage image</button>
$scope.clik = function(){
setTimeout(function (){
alert('xxx')
$scope.ca = "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTQDjJroJg1iyhupdjD6h3xslZw7UGyza9Fafv05zjlbwoQt6_D"
},1000)
}
You have two problems. The first is you should be using $timeout so you do not have to tell angular it needs to go through a digest cycle and update all the bindings. So anywhere you have setTimeout(...) use $timeout(...)
setTimeout(function (){
alert('xxx')
$scope.ca = "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTQDjJroJg1iyhupdjD6h3xslZw7UGyza9Fafv05zjlbwoQt6_D"
},1000)
//would be
$timeout(function (){
alert('xxx')
$scope.ca = "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTQDjJroJg1iyhupdjD6h3xslZw7UGyza9Fafv05zjlbwoQt6_D"
},1000)
The second problem is you do not wait for the image to load before trying to draw it:
setTimeout(()=>{
resetImage();
},0)
This is not long enough to allow the image to load. Instead use a load event to detect when it has loaded and then run resetImage().
angular.element("#image").bind('load', resetImage);
Demo
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope, $timeout) {
$scope.ca = 'https://media.glassdoor.com/brand-logo/white-logotype/glassdoor-logo.jpg'
$scope.imageArray = ['https://pbs.twimg.com/profile_images/2504398687/344204969_400x400.jpg', 'https://media.glassdoor.com/brand-logo/white-logotype/glassdoor-logo.jpg'];
$scope.getImage = function(data) {
return data;
};
$scope.onImageClick = function(data, index) {
$scope.ca = data;
$scope.currentImageIndex = index;
};
$scope.clik = function() {
$timeout(function() {
$scope.ca = "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTQDjJroJg1iyhupdjD6h3xslZw7UGyza9Fafv05zjlbwoQt6_D";
}, 1000);
};
})
app.directive('imageViewer', function($timeout) {
return {
restrict: 'EA',
template: '<div style="padding:10px;">\
<button id="girardir" class="btn btn-primary btn-sm" ng-disabled="noImage"><span class="glyphicon glyphicon-menu-left"> </span> Rotate Anti-clockwise</button>\
<button id="giraresq" class="btn btn-primary btn-sm" ng-disabled="noImage">Rotate Clockwise <span class="glyphicon glyphicon-menu-right"> </span></button>\
<button id="zoomIn" class="btn btn-info btn-sm" ng-disabled="noImage"><span class="glyphicon glyphicon-zoom-in"> </span> Zoom In</button>\
<button id="zoomOut" class="btn btn-info btn-sm" ng-disabled="noImage"><span class="glyphicon glyphicon-zoom-out"> </span> Zoom Out</button>\
</div>\
<div id="image-zoom" style="padding:10px;">\
<h2 class="text-center text-danger" id="error-message" style="border:1px solid #000;display:none;padding:20px">Image Not Available</h2>\
<canvas id="canvas" height="350" data-girar="0" style="border:1px solid #000;z-index:555555;cursor:grab;position:inherit;">sdsd</canvas>\
<img ng-src="{{image}}" id="image" (load)="resetImage()" style="display:none" /> </div>',
scope: {
src: '='
},
link: function(scope, element, attr) {
scope.$watch('src', function(src) {
if (src) {
scope.image = src;
}
});
scope.noImage = false;
var canvas = document.getElementById('canvas');
var image = document.getElementById('image');
var element = canvas.getContext("2d");
var angleInDegrees = 0;
var zoomDelta = 0.1;
var currentScale = 1;
var currentAngle = 0;
var canvasWidth = 500;
var novosDadosTRBL;
var novosDadosWH;
var novosDadosW;
var novosDadosH;
var startX, startY, isDown = false;
scope.flag = 1;
$timeout(function() {
canvas.width = angular.element('#image-zoom').width();
canvas.width = canvasWidth;
}, 0);
angular.element('#carregar').click(function() {
angular.element('#image').on('load', resetImage())
.on('error', function() {
angular.element('#canvas').hide();
scope.noImage = true;
angular.element('#error-message').show();
console.log("error loading image");
});
});
//add image load event
angular.element("#image").bind('load', resetImage);
function resetImage() {
image = document.getElementById('image');
element = canvas.getContext("2d");
angleInDegrees = 0;
currentScale = 1;
currentAngle = 0;
if (scope.flag) {
scope.flag = 0;
drawImage();
element.translate(canvas.width / 2, canvas.height / 2);
$timeout(function() {
angular.element('#canvas').attr('data-girar', 0);
drawImage();
}, 0);
} else {
element.translate(0, 0);
angular.element('#canvas').attr('data-girar', 0);
drawImage();
}
};
angular.element('#giraresq').click(function() {
angleInDegrees = 90;
currentAngle += angleInDegrees;
drawImage();
});
angular.element('#girardir').click(function() {
angleInDegrees = -90;
currentAngle += angleInDegrees;
drawImage();
});
angular.element('#zoomIn').click(function() {
currentScale += zoomDelta;
drawImage();
});
angular.element('#canvas').bind('mousewheel DOMMouseScroll', function(event) {
if (event.originalEvent.wheelDelta > 0 || event.originalEvent.detail < 0) {
currentScale += zoomDelta;
drawImage();
} else {
if (currentScale - zoomDelta - 0.1 > 0) {
currentScale -= zoomDelta;
drawImage();
}
}
});
angular.element('#zoomOut').click(function() {
if (currentScale > 0.12) {
currentScale -= zoomDelta;
}
drawImage();
});
canvas.onmousedown = function(e) {
var pos = getMousePos(canvas, e);
startX = pos.x;
startY = pos.y;
isDown = true;
}
canvas.onmousemove = function(e) {
if (isDown === true) {
var pos = getMousePos(canvas, e);
var x = pos.x;
var y = pos.y;
element.translate(x - startX, y - startY);
drawImage();
startX = x;
startY = y;
}
}
window.onmouseup = function(e) {
isDown = false;
}
function drawImage() {
clear();
element.save();
element.scale(currentScale, currentScale);
element.rotate(currentAngle * Math.PI / 180);
element.drawImage(image, -image.width / 2, -image.height / 2);
element.restore();
}
function clear() {
element.clearRect(-2000, -2000, 5000, 5000);
}
function getMousePos(canvas, evt) {
var rect = canvas.getBoundingClientRect();
return {
x: evt.clientX - rect.left,
y: evt.clientY - rect.top
};
}
}
}
});
.error {
corder: 1px solid red;
}
.imgContainer ul {
display: flex;
margin: 0;
padding: 0;
list-style: none;
overflow-x: scroll;
width: 100%;
}
.imgContainer ul li {
margin-left: 5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script data-require="angular.js#1.5.x" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.11/angular.min.js" data-semver="1.5.11"></script>
<div ng-app="plunker" ng-controller="MainCtrl">
<div class="imgContainer" ng-if="imageArray && imageArray.length">
<ul>
<li ng-repeat="img in imageArray"><img data-ng-src="{{getImage(img)}}" width="100" height="100" ng-click="onImageClick(img,$index)" /></li>
</ul>
</div>
<image-viewer src="ca"></image-viewer>
<button ng-click="clik()">chnage image</button>
</div>
Plunker if needed

fabric.js free drawing after shape error

I have a problem with fabric.js. I can draw a square in the canvas, but if I then switch to free drawing the line starts in the middle of the shape.
have a look here:
jsfiddle
var functouse = "pencil";
var pensize = 5;
var pencolour = "#000000";
var fillcolour = "#ffffff";
var canvas = new fabric.Canvas('sketchpad', {
isDrawingMode: true
});
fabric.Object.prototype.transparentCorners = false;
canvas.selection = false;
canvas.observe('mouse:down', function(e) {
mousedown(e);
});
canvas.observe('mouse:move', function(e) {
mousemove(e);
});
canvas.observe('mouse:up', function(e) {
mouseup(e);
});
canvas.observe('object:selected ', function(e) {
console.log('selected something');
});
//fabric.Object.prototype.transparentCorners = false;
var line;
var isDown;
var initX = 0;
var initY = 0;
$(".top_butt").click(function() {
functouse = $(this).attr('data-id');
});
function mousedown(o) {
isDown = true;
var pointer = canvas.getPointer(o.e);
if (functouse == "pencil") {
canvas.isDrawingMode = true;
canvas.freeDrawingColor = pencolour;
canvas.freeDrawingLineWidth = pensize;
canvas.freeDrawingMode = 'Pencil';
} else if (functouse == "square") {
initX = pointer.x;
initY = pointer.y;
canvas.isDrawingMode = false;
var square = new fabric.Rect({
width: 0.1,
height: 0.1,
left: initX,
top: initY,
fill: fillcolour,
stroke: pencolour,
strokeWidth: pensize,
selectable: false,
hasBorders: false,
hasControls: false
});
canvas.add(square);
canvas.setActiveObject(square);
}
}
function mousemove(o) {
if (!isDown) return;
var pointer = canvas.getPointer(o.e);
if (functouse == "square") {
var ww = Math.abs(pointer.x - initX);
var hh = Math.abs(pointer.y - initY);
if (!ww || !hh) {
return false;
}
var square = canvas.getActiveObject();
square.set('width', ww).set('height', hh);
canvas.renderAll();
} else if (functouse == "pencil") {
if (initX == -1 || initY == -1) {
initX = pointer.x;
initY = pointer.y;
}
}
}
function mouseup(o) {
isDown = false;
if (functouse == "square") {
initX = -1;
initY = -1;
var square = canvas.getActiveObject();
square.setCoords();
//canvas.add(square);
canvas.renderAll();
//canvas.pointer
$('canvas').css('cursor', 'nw-resize');
} else if (functouse == "pencil") {
canvas.forEachObject(function(o) {
o.selectable = false,
o.lockMovementX = true,
o.lockMovementY = true,
o.lockScaling = true
});
}
}
p span{
cursor: pointer;
}
canvas{
border: solid thin #ccc;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.1.0/fabric.all.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<p><span class="top_butt" data-id='square'>Square</span> | <span class="top_butt" data-id='pencil'>Pencil</span></p>
<canvas id="sketchpad" width="400" height="600"></canvas>
<p>
Uno y dos
</p>
draw a square, then a line and you will see what I mean.
extra point for: I don't understand why it starts drawing with a very thin line and only when the line is finished it adopts the line size I set.
and on a third bonus point: is it possible to draw the squares from the top left corners, instead of the center.
You need to remove the event handler using off() , and I have updated your fabric version . Have a look.
DEMO
var functouse = "pencil";
var pensize = 5;
var pencolour = "#000000";
var fillcolour = "#ffffff";
var canvas = new fabric.Canvas('sketchpad', {
isDrawingMode: true
});
fabric.Object.prototype.transparentCorners = false;
canvas.selection = false;
canvas.on('object:selected ', function(e) {
console.log('selected something');
});
//fabric.Object.prototype.transparentCorners = false;
var line;
var isDown;
var square;
var initX = 0;
var initY = 0;
$(".top_butt").click(function() {
functouse = $(this).attr('data-id');
removeEvents();
if (functouse == "pencil") {
setObjectSelectable(false);
canvas.isDrawingMode = true;
canvas.freeDrawingColor = pencolour;
canvas.freeDrawingLineWidth = pensize;
canvas.freeDrawingMode = 'Pencil';
} else if (functouse == "square") {
canvas.isDrawingMode = false;
setObjectSelectable(false);
addEvent();
} else {
canvas.isDrawingMode = false;
setObjectSelectable(true);
}
});
function setObjectSelectable(val) {
canvas.forEachObject(function(obj) {
obj.selectable = val;
})
canvas.renderAll();
}
function removeEvents() {
canvas.off('mouse:down');
canvas.off('mouse:move');
canvas.off('mouse:up');
}
function addEvent() {
canvas.on('mouse:down', mousedown);
canvas.on('mouse:move', mousemove);
canvas.on('mouse:up', mouseup);
}
function mousedown(o) {
isDown = true;
var pointer = canvas.getPointer(o.e);
initX = pointer.x;
initY = pointer.y;
canvas.isDrawingMode = false;
square = new fabric.Rect({
width: 0.1,
height: 0.1,
left: initX,
top: initY,
fill: fillcolour,
stroke: pencolour,
strokeWidth: pensize,
selectable: false,
hasBorders: false,
hasControls: false
});
canvas.add(square);
canvas.setActiveObject(square);
}
function mousemove(o) {
if (!isDown) return;
var pointer = canvas.getPointer(o.e);
var ww = Math.abs(pointer.x - initX);
var hh = Math.abs(pointer.y - initY);
if (!ww || !hh) {
return false;
}
square.set('width', ww).set('height', hh);
canvas.renderAll();
}
function mouseup(o) {
isDown = false;
initX = -1;
initY = -1;
square.setCoords();
square = null;
//canvas.add(square);
canvas.renderAll();
}
p span{
cursor: pointer;
}
canvas{
border: solid thin #ccc;
}
<script src="https://rawgit.com/kangax/fabric.js/master/dist/fabric.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p><span class="top_butt" data-id='square'>Square</span> | <span class="top_butt" data-id='pencil'>Pencil</span>| <span class="top_butt" data-id='selection'>Selection</span></p>
<canvas id="sketchpad" width="400" height="600"></canvas>
<p>
Uno y dos
</p>

Fabric js : fabric js drawing mode and selection mode options

I'm using fabric js to develop a application to draw a line, Rectangle and circle in one canvas.And there is a other function to drag and drop a image on to canvas.
But when i added drag and drop function to the application other three function are not working.
I have found this article. But i was unable to integrate it with my one.
function initCanvas() {
$('.canvas-container').each(function (index) {
var canvasContainer = $(this)[0];
var canvasObject = $("canvas", this)[0];
var url = $(this).data('floorplan');
var canvas = window._canvas = new fabric.Canvas(canvasObject);
canvas.setHeight(400);
canvas.setWidth(500);
canvas.setBackgroundImage(url, canvas.renderAll.bind(canvas));
var imageOffsetX, imageOffsetY;
function handleDragStart(e) {
[].forEach.call(images, function (img) {
img.classList.remove('img_dragging');
});
this.classList.add('img_dragging');
var imageOffset = $(this).offset();
imageOffsetX = e.clientX - imageOffset.left;
imageOffsetY = e.clientY - imageOffset.top;
}
function handleDragOver(e) {
if (e.preventDefault) {
e.preventDefault();
}
e.dataTransfer.dropEffect = 'copy';
return false;
}
function handleDragEnter(e) {
this.classList.add('over');
}
function handleDragLeave(e) {
this.classList.remove('over');
}
function handleDrop(e) {
e = e || window.event;
if (e.preventDefault) {
e.preventDefault();
}
if (e.stopPropagation) {
e.stopPropagation();
}
var img = document.querySelector('.furniture img.img_dragging');
console.log('event: ', e);
var offset = $(canvasObject).offset();
var y = e.clientY - (offset.top + imageOffsetY);
var x = e.clientX - (offset.left + imageOffsetX);
var newImage = new fabric.Image(img, {
width: img.width,
height: img.height,
left: x,
top: y
});
canvas.add(newImage);
return false;
}
function handleDragEnd(e) {
[].forEach.call(images, function (img) {
img.classList.remove('img_dragging');
});
}
var images = document.querySelectorAll('.furniture img');
[].forEach.call(images, function (img) {
img.addEventListener('dragstart', handleDragStart, false);
img.addEventListener('dragend', handleDragEnd, false);
});
canvasContainer.addEventListener('dragenter', handleDragEnter, false);
canvasContainer.addEventListener('dragover', handleDragOver, false);
canvasContainer.addEventListener('dragleave', handleDragLeave, false);
canvasContainer.addEventListener('drop', handleDrop, false);
});
}
initCanvas();
var canvas = new fabric.Canvas('canvas1', { selection: false });
var line, isDown;
function myFun() {
removeEvents();
canvas.on('mouse:down', function (o) {
isDown = true;
var pointer = canvas.getPointer(o.e);
var points = [pointer.x, pointer.y, pointer.x, pointer.y];
line = new fabric.Line(points, {
strokeWidth: 5,
fill: '#07ff11a3',
stroke: '#07ff11a3',
originX: 'center',
originY: 'center'
});
canvas.add(line);
});
canvas.on('mouse:move', function (o) {
if (!isDown) return;
var pointer = canvas.getPointer(o.e);
line.set({ x2: pointer.x, y2: pointer.y });
canvas.renderAll();
});
canvas.on('mouse:up', function (o) {
isDown = false;
});
canvas.selection = false;
}
function drawrec() {
var line, isDown, origX, origY;
removeEvents();
canvas.on('mouse:down', function (o) {
isDown = true;
var pointer = canvas.getPointer(o.e);
origX = pointer.x;
origY = pointer.y;
var pointer = canvas.getPointer(o.e);
line = new fabric.Rect({
left: origX,
top: origY,
originX: 'left',
originY: 'top',
width: pointer.x - origX,
height: pointer.y - origY,
angle: 0,
fill: '#07ff11a3',
stroke: 'black',
transparentCorners: false
});
canvas.add(line);
});
canvas.on('mouse:move', function (o) {
if (!isDown) return;
var pointer = canvas.getPointer(o.e);
if (origX > pointer.x) {
line.set({ left: Math.abs(pointer.x) });
}
if (origY > pointer.y) {
line.set({ top: Math.abs(pointer.y) });
}
line.set({ width: Math.abs(origX - pointer.x) });
line.set({ height: Math.abs(origY - pointer.y) });
canvas.renderAll();
});
canvas.on('mouse:up', function (o) {
isDown = false;
});
}
function drawcle() {
var circle, isDown, origX, origY;
removeEvents();
canvas.on('mouse:down', function (o) {
isDown = true;
var pointer = canvas.getPointer(o.e);
origX = pointer.x;
origY = pointer.y;
circle = new fabric.Circle({
left: pointer.x,
top: pointer.y,
radius: 1,
strokeWidth: 1,
fill: '#07ff11a3',
stroke: 'black',
selectable: false,
originX: 'center', originY: 'center'
});
canvas.add(circle);
});
canvas.on('mouse:move', function (o) {
if (!isDown) return;
var pointer = canvas.getPointer(o.e);
circle.set({ radius: Math.abs(origX - pointer.x) });
canvas.renderAll();
});
canvas.on('mouse:up', function (o) {
isDown = false;
});
}
function removeEvents() {
canvas.off('mouse:down');
canvas.off('mouse:up');
canvas.off('mouse:move');
}
<div class="fullpage">
<div class="section">
<a class="thmb" href="#" onclick="myFun()" style="padding: 0px 10px;margin:5px;border: 2px solid;">line</a>
<a class="thmb" href="#" onclick="drawrec()" style="padding: 0px 10px;margin:5px;border: 2px solid;">Rectangle</a>
<a class="thmb" href="#" onclick="drawcle()" style="padding: 0px 10px;margin:5px;border: 2px solid;">Circle</a>
<div class="canvas-container">
<canvas id="canvas1" style="border: 1px solid;width: 500px;height: 500px"></canvas>
</div>
<div class="furniture" style="padding: 20px;border: 1px solid;width: 460px">
<h3>Drag the image to canvas</h3>
<img draggable="true" src="https://www.mve.com/media/Move_logo_-01.png" width="60">
</div>
</div>
</div>
<script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js'></script>
<script src='https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.7.6/fabric.min.js'></script>
var canvas = window._canvas = new fabric.Canvas(canvasObject);
inside initCanvas() you are again creating fabric canvas, so remove it. And to enable free drawing you need to do canvas.isDrawingMode = true
function initCanvas() {
$('.canvas-container').each(function(index) {
var canvasContainer = $(this)[0];
var canvasObject = $("canvas", this)[0];
var imageOffsetX, imageOffsetY;
function handleDragStart(e) {
[].forEach.call(images, function(img) {
img.classList.remove('img_dragging');
});
this.classList.add('img_dragging');
var imageOffset = $(this).offset();
imageOffsetX = e.clientX - imageOffset.left;
imageOffsetY = e.clientY - imageOffset.top;
}
function handleDragOver(e) {
if (e.preventDefault) {
e.preventDefault();
}
e.dataTransfer.dropEffect = 'copy';
return false;
}
function handleDragEnter(e) {
this.classList.add('over');
}
function handleDragLeave(e) {
this.classList.remove('over');
}
function handleDrop(e) {
e = e || window.event;
if (e.preventDefault) {
e.preventDefault();
}
if (e.stopPropagation) {
e.stopPropagation();
}
var img = document.querySelector('.furniture img.img_dragging');
console.log('event: ', e);
var offset = $(canvasObject).offset();
var y = e.clientY - (offset.top + imageOffsetY);
var x = e.clientX - (offset.left + imageOffsetX);
var newImage = new fabric.Image(img, {
width: img.width,
height: img.height,
left: x,
top: y
});
canvas.add(newImage);
return false;
}
function handleDragEnd(e) {
[].forEach.call(images, function(img) {
img.classList.remove('img_dragging');
});
}
var images = document.querySelectorAll('.furniture img');
[].forEach.call(images, function(img) {
img.addEventListener('dragstart', handleDragStart, false);
img.addEventListener('dragend', handleDragEnd, false);
});
canvasContainer.addEventListener('dragenter', handleDragEnter, false);
canvasContainer.addEventListener('dragover', handleDragOver, false);
canvasContainer.addEventListener('dragleave', handleDragLeave, false);
canvasContainer.addEventListener('drop', handleDrop, false);
});
}
initCanvas();
var canvas = new fabric.Canvas('canvas1', {
selection: false
});
var line, isDown;
function drawLine() {
removeEvents();
changeObjectSelection(false);
canvas.on('mouse:down', function(o) {
isDown = true;
var pointer = canvas.getPointer(o.e);
var points = [pointer.x, pointer.y, pointer.x, pointer.y];
line = new fabric.Line(points, {
strokeWidth: 5,
fill: '#07ff11a3',
stroke: '#07ff11a3',
originX: 'center',
originY: 'center',
selectable: false
});
canvas.add(line);
});
canvas.on('mouse:move', function(o) {
if (!isDown) return;
var pointer = canvas.getPointer(o.e);
line.set({
x2: pointer.x,
y2: pointer.y
});
canvas.renderAll();
});
canvas.on('mouse:up', function(o) {
isDown = false;
line.setCoords();
});
}
function drawrec() {
var rect, isDown, origX, origY;
removeEvents();
changeObjectSelection(false);
canvas.on('mouse:down', function(o) {
isDown = true;
var pointer = canvas.getPointer(o.e);
origX = pointer.x;
origY = pointer.y;
var pointer = canvas.getPointer(o.e);
rect = new fabric.Rect({
left: origX,
top: origY,
originX: 'left',
originY: 'top',
width: pointer.x - origX,
height: pointer.y - origY,
angle: 0,
selectable:false,
fill: '#07ff11a3',
stroke: 'black',
transparentCorners: false
});
canvas.add(rect);
});
canvas.on('mouse:move', function(o) {
if (!isDown) return;
var pointer = canvas.getPointer(o.e);
if (origX > pointer.x) {
rect.set({
left: Math.abs(pointer.x)
});
}
if (origY > pointer.y) {
rect.set({
top: Math.abs(pointer.y)
});
}
rect.set({
width: Math.abs(origX - pointer.x)
});
rect.set({
height: Math.abs(origY - pointer.y)
});
canvas.renderAll();
});
canvas.on('mouse:up', function(o) {
isDown = false;
rect.setCoords();
});
}
function drawcle() {
var circle, isDown, origX, origY;
removeEvents();
changeObjectSelection(false);
canvas.on('mouse:down', function(o) {
isDown = true;
var pointer = canvas.getPointer(o.e);
origX = pointer.x;
origY = pointer.y;
circle = new fabric.Circle({
left: pointer.x,
top: pointer.y,
radius: 1,
strokeWidth: 1,
fill: '#07ff11a3',
stroke: 'black',
selectable: false,
originX: 'center',
originY: 'center'
});
canvas.add(circle);
});
canvas.on('mouse:move', function(o) {
if (!isDown) return;
var pointer = canvas.getPointer(o.e);
circle.set({
radius: Math.abs(origX - pointer.x)
});
canvas.renderAll();
});
canvas.on('mouse:up', function(o) {
isDown = false;
circle.setCoords();
});
}
function enableFreeDrawing(){
removeEvents();
canvas.isDrawingMode = true;
}
function enableSelection() {
removeEvents();
changeObjectSelection(true);
canvas.selection = true;
}
function changeObjectSelection(value) {
canvas.forEachObject(function (obj) {
obj.selectable = value;
});
canvas.renderAll();
}
function removeEvents() {
canvas.isDrawingMode = false;
canvas.selection = false;
canvas.off('mouse:down');
canvas.off('mouse:up');
canvas.off('mouse:move');
}
<div class="fullpage">
<div class="section">
<a class="thmb" href="#" onclick="drawLine()" style="padding: 0px 10px;margin:5px;border: 2px solid;">line</a>
<a class="thmb" href="#" onclick="drawrec()" style="padding: 0px 10px;margin:5px;border: 2px solid;">Rectangle</a>
<a class="thmb" href="#" onclick="drawcle()" style="padding: 0px 10px;margin:5px;border: 2px solid;">Circle</a>
<a class="thmb" href="#" onclick="enableFreeDrawing()" style="padding: 0px 10px;margin:5px;border: 2px solid;">Drawing</a>
<a class="thmb" href="#" onclick="enableSelection()" style="padding: 0px 10px;margin:5px;border: 2px solid;">Selection</a>
<div class="canvas-container">
<canvas id="canvas1" style="border: 1px solid;width: 500px;height: 500px"></canvas>
</div>
<div class="furniture" style="padding: 20px;border: 1px solid;width: 460px">
<h3>Drag the image to canvas</h3>
<img draggable="true" src="https://www.mve.com/media/Move_logo_-01.png" width="60">
</div>
</div>
</div>
<script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js'></script>
<script src='https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.7.6/fabric.min.js'></script>
Perfect solution for this is here :
var canvas = this.__canvas = new fabric.Canvas('c', {
isDrawingMode: true
});
For more just visit this fabricjs page...
Fabric js : fabric js drawing mode and selection mode options

Mouse Position In canvas not correct when page scrolls down

I've got a page where I added a canvas which will be used by a technician or client for their signatures. I've managed to get it working and able to draw inside the canvas. However, when the page is scrolled a bit downwards the positioning of where the drawing starts is higher than the mouse point. When I scroll the page back to the top again, the position of the where the drawing starts is directly on the mouse point again.
How do I get the correct position of X and Y irrespective of whether the page is scrolled or not?
This is what I've done:
HTML:
<body onload="init();">
<div id="dialogSignature" runat="server" style="padding-top:10px; display:none; ">
<canvas id="myCanvas" width="400" height="200" style="border:2px solid;"></canvas>
<img id="canvasimg" style="position:absolute;top:10%;left:52%;" style="display:none;">
</body>
<table>
<tr>
<td>
<input type="button" value="Clear" id="clr" size="23" onclick="erase()" class="myButton" >
</td>
<td>
<button class="myButton" onclick="javascript:UploadPic();return false;">Sumbit</button>
</td>
</tr>
</table>
<asp:Label ID="lblText" runat="server" Text="Label" Visible="false"></asp:Label>
<asp:Label ID="lblScopeIdentity" runat="server" Text="sss" Visible="false"></asp:Label>
</div>
Javascript:
<script type="text/javascript">
var canvas, ctx, flag = false,
prevX = 0,
currX = 0,
prevY = 0,
currY = 0,
dot_flag = false;
var x = "black",
y = 2;
function init() {
canvas = document.getElementById('myCanvas');
ctx = canvas.getContext("2d");
w = canvas.width;
h = canvas.height;
canvas.addEventListener("mousemove", function (e) {
findxy('move', e)
}, false);
canvas.addEventListener("mousedown", function (e) {
findxy('down', e)
}, false);
canvas.addEventListener("mouseup", function (e) {
findxy('up', e)
}, false);
canvas.addEventListener("mouseout", function (e) {
findxy('out', e)
}, false);
canvas.addEventListener("touchstart", function (e) {
mousePos = getTouchPos(canvas, e);
var touch = e.touches[0];
var mouseEvent = new MouseEvent("mousedown", {
clientX: touch.clientX,
clientY: touch.clientY
});
canvas.dispatchEvent(mouseEvent);
}, false);
canvas.addEventListener("touchend", function (e) {
var mouseEvent = new MouseEvent("mouseup", {});
canvas.dispatchEvent(mouseEvent);
}, false);
canvas.addEventListener("touchmove", function (e) {
var touch = e.touches[0];
var mouseEvent = new MouseEvent("mousemove", {
clientX: touch.clientX,
clientY: touch.clientY
});
canvas.dispatchEvent(mouseEvent);
}, false);
// Prevent scrolling when touching the canvas
document.body.addEventListener("touchstart", function (e) {
if (e.target == canvas) {
e.preventDefault();
}
}, false);
document.body.addEventListener("touchend", function (e) {
if (e.target == canvas) {
e.preventDefault();
}
}, false);
document.body.addEventListener("touchmove", function (e) {
if (e.target == canvas) {
e.preventDefault();
}
}, false);
}
function getTouchPos(canvasDom, touchEvent) {
var rect = canvasDom.getBoundingClientRect();
return {
x: touchEvent.touches[0].clientX - rect.left,
y: touchEvent.touches[0].clientY - rect.top
};
}
function color(obj) {
switch (obj.id) {
case "green":
x = "green";
break;
case "blue":
x = "blue";
break;
case "red":
x = "red";
break;
case "yellow":
x = "yellow";
break;
case "orange":
x = "orange";
break;
case "black":
x = "black";
break;
case "white":
x = "white";
break;
}
if (x == "white") y = 14;
else y = 2;
}
function draw() {
ctx.beginPath();
ctx.moveTo(prevX, prevY);
ctx.lineTo(currX, currY);
ctx.strokeStyle = x;
ctx.lineWidth = y;
ctx.stroke();
ctx.closePath();
}
function erase() {
var m = confirm("Want to clear");
if (m) {
ctx.clearRect(0, 0, w, h);
document.getElementById("canvasimg").style.display = "none";
}
}
function save() {
document.getElementById("canvasimg").style.border = "2px solid";
var dataURL = canvas.toDataURL();
document.getElementById("canvasimg").src = dataURL;
document.getElementById("canvasimg").style.display = "inline";
}
function findxy(res, e) {
if (res == 'down') {
prevX = currX;
prevY = currY;
currX = e.clientX - canvas.offsetLeft;
currY = e.clientY - canvas.offsetTop;
flag = true;
dot_flag = true;
if (dot_flag) {
ctx.beginPath();
ctx.fillStyle = x;
ctx.fillRect(currX, currY, 2, 2);
ctx.closePath();
dot_flag = false;
}
}
if (res == 'up' || res == "out") {
flag = false;
}
if (res == 'move') {
if (flag) {
prevX = currX;
prevY = currY;
currX = e.clientX - canvas.offsetLeft;
currY = e.clientY - canvas.offsetTop;
draw();
}
}
}
var scopeIdentityUse = "<%=scopeIdentityJS1%>";
var Pic = document.getElementById("myCanvas").toDataURL("image/png");
Pic = Pic.replace(/^data:image\/(png|jpg);base64,/, "")
$.ajax({
type: 'POST',
url: 'Save_Picture.aspx/UploadPic',
data: '{ "imageData" : "' + Pic + '", "param" : "' + scopeIdentityUse + '" }',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (msg) {
document.location.href = 'CreatePDFReport.aspx'
//alert("Done, Picture Uploaded.");
}
});
</script>
Below is a better version of the correct position of mouse pointer. (styling needs to be redone though in stylesheet)....
Javascript:
<script type="text/javascript">
var canvas, ctx;
var mouseX, mouseY, mouseDown = 0;
var touchX, touchY;
var lastX, lastY = -1;
function init() {
canvas = document.getElementById('can');
ctx = canvas.getContext('2d');
w = canvas.width;
h = canvas.height;
canvas.addEventListener('mousedown', sketchpad_mouseDown, false);
canvas.addEventListener('mousemove', sketchpad_mouseMove, false);
canvas.addEventListener('mouseup', sketchpad_mouseUp, false);
canvas.addEventListener('touchstart', sketchpad_touchStart, false);
canvas.addEventListener('touchend', sketchpad_touchEnd, false);
canvas.addEventListener('touchmove', sketchpad_touchMove, false);
function drawLine(ctx, x, y, size) {
if (lastX == -1) {
lastX = x;
lastY = y;
}
r = 0; g = 0; b = 0; a = 255;
ctx.strokeStyle = "rgba(" + r + "," + g + "," + b + "," + (a / 255) + ")";
ctx.lineCap = "round";
ctx.beginPath();
ctx.moveTo(lastX, lastY);
ctx.lineTo(x, y);
ctx.lineWidth = size;
ctx.stroke();
ctx.closePath();
lastX = x;
lastY = y;
}
function sketchpad_mouseDown() {
mouseDown = 1;
drawLine(ctx, mouseX, mouseY, 6);
}
function sketchpad_mouseUp() {
mouseDown = 0;
lastX = -1
lastY = -1
}
function sketchpad_mouseMove(e) {
getMousePos(e);
if (mouseDown == 1) {
drawLine(ctx, mouseX, mouseY, 6);
}
}
function getMousePos(e) {
if (!e)
var e = event;
if (e.offsetX) {
mouseX = e.offsetX;
mouseY = e.offsetY;
}
else if (e.layerX) {
mouseX = e.layerX;
mouseY = e.layerY;
}
}
function sketchpad_touchStart() {
getTouchPos();
drawLine(ctx, touchX, touchY, 6);
event.preventDefault();
}
function sketchpad_touchEnd() {
lastX = -1;
lastY = -1;
}
function sketchpad_touchMove(e) {
getTouchPos(e);
drawLine(ctx, touchX, touchY, 6);
event.preventDefault();
}
function getTouchPos(e) {
if (!e)
var e = event;
if (e.touches) {
if (e.touches.length == 1) {
var touch = e.touches[0];
touchX = touch.pageX - touch.target.offsetLeft;
touchY = touch.pageY - touch.target.offsetTop;
}
}
}
function fd_erase(elem1) {
ctx.clearRect(0, 0, w, h);
if (typeof elem1 != 'undefined') {
document.getElementById(elem1).style.display = "none";
document.getElementById(elem1).value = '';
}
}
function fd_save() {
canvas = document.getElementById('can');
ctx = canvas.getContext('2d');
var dataURL = canvas.toDataURL();
document.getElementById('Signature1_img').src = dataURL;
document.getElementById('Signature1').value = dataURL;
document.getElementById('Hidden1').value = dataURL;
document.getElementById('Signature1_img').style.display = "inline";
}
And on html:
<div style="position: absolute; width:794px; height:1122px; background-color:#FFFFFF;">
<form runat="server" id="form1">
<canvas id="can" Width="300px" Height="300px" style="top:108px;left:96px;color:#000000;background-color:#FFFFFF;border:1px solid #000;"></canvas>
<input type="hidden" id="Signature1" name="Signature1" value="" >
<input type="text" id="Hidden1" name="hndText" runat="server" value="" >
<img id="Signature1_img" name="Signature1_img" Width="300px" Height="300px" style="color:#000000;background-color:#FFFFFF;border-style:solid;border-width:1px;border-color:#000000;display:none;">
</form>
</div>

Why Wont My HTML5/JS App Work On My iPhone?

How's it going guys?
Recently, with the help given from this site, I've learned how to draw a rectangle on an HTML5 canvas at the click of the button... that's not the problem:) The is problem this... unfortunately, it didn't work at all when I tried to use it on my iPhone... why:(?
Here's my code:
JAVASCRIPT:
// "Rectangle" Button
function rect()
{
var canvas = document.getElementById('canvasSignature'),
ctx = canvas.getContext('2d'),
rect = {},
drag = false;
function init() {
canvas.addEventListener('mousedown', mouseDown, false);
canvas.addEventListener('mouseup', mouseUp, false);
canvas.addEventListener('mousemove', mouseMove, false);
}
function mouseDown(e) {
rect.startX = e.pageX - this.offsetLeft;
rect.startY = e.pageY - this.offsetTop;
drag = true;
}
function mouseUp() {
drag = false;
}
function mouseMove(e) {
if (drag) {
rect.w = (e.pageX - this.offsetLeft) - rect.startX;
rect.h = (e.pageY - this.offsetTop) - rect.startY ;
draw();
}
}
function draw() {
ctx.fillRect(rect.startX, rect.startY, rect.w, rect.h);
}
init();
}
HTML5:
<div id="canvasDiv">
<canvas id="canvasSignature" width="580px" height="788px" style="border:2px solid #000; background: #FFF;"></canvas>
</div>
<div id="rect">
<p><button onclick="rect();">Rectangle</button></p>
</div>
Any help at all would be greatly appreciated:)
for first you got a mistake in you code
you star with this
rect() {
and close it only at the end of script
and on touch devices you need to use touch* events i think
something like this
var canvas = document.getElementById('canvasSignature'), ctx = canvas.getContext('2d'), rect = {}, drag = false;
function init() {
canvas.addEventListener("touchstart", touchHandler, false);
canvas.addEventListener("touchmove", touchHandler, false);
canvas.addEventListener("touchend", touchHandler, false);
}
function touchHandler(event) {
if (event.targetTouches.length == 1) { //one finger touche
var touch = event.targetTouches[0];
if (event.type == "touchstart") {
rect.startX = touch.pageX;
rect.startY = touch.pageY;
drag = true;
} else if (event.type == "touchmove") {
if (drag) {
rect.w = touch.pageX - rect.startX;
rect.h = touch.pageY - rect.startY ;
draw();
}
} else if (event.type == "touchend" || event.type == "touchcancel") {
drag = false;
}
}
}
function draw() {
ctx.fillRect(rect.startX, rect.startY, rect.w, rect.h);
}
init();

Categories