Return class element to default - javascript

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: '' });
};

Related

Auto Scaling Image Annotation

Scalize is a jQuery plugin used for adding custom markers (hotspots) with custom popovers and animations to containers or images.
But now When I click one by one on pointer it show all one by one But I am trying to show only one so when click another pointer will close the other which already opened.
Here is my EXAMPLE
(function(jQuery) {
"use strict";
//----------------------------------------//
// Variable
//----------------------------------------//
var variable = {
width : 0,
height : 0,
selector : '.item-point',
styleSelector : 'circle',
animationSelector : 'pulse2',
animationPopoverIn : 'flipInY',
animationPopoverOut : 'flipOutY',
onInit : null,
getSelectorElement : null,
getValueRemove : null
}
//----------------------------------------//
// Scaling
//----------------------------------------//
var scaling = {
settings : null,
//----------------------------------------//
// Initialize
//----------------------------------------//
init: function(el, options){
this.settings = jQuery.extend(variable, options);
this.event(el);
scaling.layout(el);
jQuery(window).on('load', function(){
scaling.layout(el);
});
jQuery(el).find('.target').on('load', function(){
scaling.layout(el);
});
jQuery(window).on('resize', function(){
scaling.layout(el);
});
},
//----------------------------------------//
// Event
//----------------------------------------//
event : function(elem){
// Set Style Selector
if ( this.settings.styleSelector ) {
jQuery(this.settings.selector).addClass( this.settings.styleSelector );
}
// Set Animation
if ( this.settings.animationSelector ) {
if( this.settings.animationSelector == 'marker' ){
jQuery(this.settings.selector).addClass( this.settings.animationSelector );
jQuery(this.settings.selector).append('<div class="pin"></div>')
jQuery(this.settings.selector).append('<div class="pulse"></div>')
}else{
jQuery(this.settings.selector).addClass( this.settings.animationSelector );
}
}
// Event On Initialize
if ( jQuery.isFunction( this.settings.onInit ) ) {
this.settings.onInit();
}
// Content add class animated element
jQuery(elem).find('.content').addClass('animated');
// Wrapper selector
jQuery(this.settings.selector).wrapAll( "<div class='wrap-selector' />");
// Event Selector
jQuery(this.settings.selector).each(function(){
// Toggle
jQuery('.toggle', this).on('click', function(e){
e.preventDefault();
jQuery(this).closest(scaling.settings.selector).toggleClass('active');
// Selector Click
var content = jQuery(this).closest(scaling.settings.selector).data('popover'),
id = jQuery(content);
if(jQuery(this).closest(scaling.settings.selector).hasClass('active') && !jQuery(this).closest(scaling.settings.selector).hasClass('disabled')){
if ( jQuery.isFunction( scaling.settings.getSelectorElement ) ) {
scaling.settings.getSelectorElement(jQuery(this).closest(scaling.settings.selector));
}
id.fadeIn(500,function(){
if( getBrowserName() == "Safari" ){
setTimeout(function(){
id.removeClass('flipInY');
},125);
}
});
scaling.layout(elem);
id.removeClass(scaling.settings.animationPopoverOut);
id.addClass(scaling.settings.animationPopoverIn);
}else{
if(jQuery.isFunction( scaling.settings.getValueRemove )){
scaling.settings.getValueRemove(jQuery(this).closest(scaling.settings.selector));
}
id.removeClass(scaling.settings.animationPopoverIn);
id.addClass(scaling.settings.animationPopoverOut);
id.delay(500).fadeOut();
}
});
// Exit
var target = jQuery(this).data('popover'),
idTarget = jQuery(target);
idTarget.find('.exit').on('click', function(e){
e.preventDefault();
// selector.removeClass('active');
jQuery('[data-popover="'+ target +'"]').removeClass('active');
idTarget.removeClass(scaling.settings.animationPopoverIn);
idTarget.addClass(scaling.settings.animationPopoverOut);
idTarget.delay(500).fadeOut();
});
});
},
//----------------------------------------//
// Layout
//----------------------------------------//
layout : function(elem){
// Get Original Image
var image = new Image();
image.src = elem.find('.target').attr("src");
// Variable
var width = image.naturalWidth,
height = image.naturalHeight,
getWidthLess = jQuery(elem).width(),
setPersenWidth = getWidthLess/width * 100,
setHeight = height * setPersenWidth / 100;
// Set Heigh Element
jQuery(elem).css("height", setHeight);
// Resize Width
if( jQuery(window).width() < width ){
jQuery(elem).stop().css("width","100%");
}else{
jQuery(elem).stop().css("width",width);
}
// Set Position Selector
jQuery(this.settings.selector).each(function(){
if( jQuery(window).width() < width ){
var getTop = jQuery(this).data("top") * setPersenWidth / 100,
getLeft = jQuery(this).data("left") * setPersenWidth / 100;
}else{
var getTop = jQuery(this).data("top"),
getLeft = jQuery(this).data("left");
}
jQuery(this).css("top", getTop + "px");
jQuery(this).css("left", getLeft + "px");
// Target Position
var target = jQuery(this).data('popover'),
allSize = jQuery(target).find('.head').outerHeight() + jQuery(target).find('.body').outerHeight() + jQuery(target).find('.footer').outerHeight();
jQuery(target).css("left", getLeft + "px");
jQuery(target).css("height", allSize + "px");
if(jQuery(target).hasClass('bottom')){
var getHeight = jQuery(target).outerHeight(),
getTopBottom = getTop - getHeight;
jQuery(target).css("top", getTopBottom + "px");
}else if(jQuery(target).hasClass('center')){
var getHeight = jQuery(target).outerHeight() * 0.50,
getTopBottom = getTop - getHeight;
jQuery(target).css("top", getTopBottom + "px");
}else{
jQuery(target).css("top", getTop + "px");
}
jQuery('.toggle', this).css('width', jQuery(this).outerWidth());
jQuery('.toggle', this).css('height', jQuery(this).outerHeight());
// Toggle Size
if(jQuery(this).find('.pin')){
var widthThis = jQuery('.pin', this).outerWidth(),
heightThis = jQuery('.pin', this).outerHeight();
jQuery('.toggle', this).css('width', widthThis);
jQuery('.toggle', this).css('height', heightThis);
}
});
}
};
//----------------------------------------//
// Scalize Plugin
//----------------------------------------//
jQuery.fn.scalize = function(options){
return scaling.init(this, options);
};
}(jQuery));
function getBrowserName() {
var name = "Unknown";
if(navigator.userAgent.indexOf("MSIE")!=-1){
name = "MSIE";
}
else if(navigator.userAgent.indexOf("Firefox")!=-1){
name = "Firefox";
}
else if(navigator.userAgent.indexOf("Opera")!=-1){
name = "Opera";
}
else if(navigator.userAgent.indexOf("Chrome") != -1){
name = "Chrome";
}
else if(navigator.userAgent.indexOf("Safari")!=-1){
name = "Safari";
}
return name;
}
Add this to your initialisation:
getSelectorElement: function(el) {
$('.item-point.active').not($(el)[0]).find('.toggle').click();
}
This hooks into the getSelectorElement method in the Scalize plugin and triggers a click on any active (open) elements that don't match the most recently clicked item.
Add it like so:
$(document).ready(function(){
$('.scalize').scalize({
styleSelector: 'circle',
animationPopoverIn: 'fadeIn',
animationPopoverOut: 'fadeOut',
animationSelector: 'pulse2',
getSelectorElement: function(el) {
$('.item-point.active').not($(el)[0]).find('.toggle').click();
}
});
});
Note, because this is hooking into existing methods in the plugin it's a little safer (no unpredictable side effects, plus you get the intended transition out on the disappearing elements). Fiddle.
I've modified your jsFiddle to work.
TL;DR: Anytime an point is clicked, if there are other active siblings, loop over them and hide their popups.
It isn't a pretty way of doing it but it is working in the Fiddle.
$('.scalize').on('click', '.item-point', (function() {
$(this).siblings('.item-point.active').each(function() {
var popover = $(this).data('popover');
$(popover).removeClass('fadeIn').css({
'display': 'none'
});
$(this).removeClass('active');
});
}));

rotating SVG rect around its center using vanilla JavaScript

This is not a duplicate of the other question.
I found this talking about rotation about the center using XML, tried to implement the same using vanilla JavaScript like rotate(45, 60, 60) but did not work with me.
The approach worked with me is the one in the snippet below, but found the rect not rotating exactly around its center, and it is moving little bit, the rect should start rotating upon the first click, and should stop at the second click, which is going fine with me.
Any idea, why the item is moving, and how can I fix it.
var NS="http://www.w3.org/2000/svg";
var SVG=function(el){
return document.createElementNS(NS,el);
}
var svg = SVG("svg");
svg.width='100%';
svg.height='100%';
document.body.appendChild(svg);
class myRect {
constructor(x,y,h,w,fill) {
this.SVGObj= SVG('rect'); // document.createElementNS(NS,"rect");
self = this.SVGObj;
self.x.baseVal.value=x;
self.y.baseVal.value=y;
self.width.baseVal.value=w;
self.height.baseVal.value=h;
self.style.fill=fill;
self.onclick="click(evt)";
self.addEventListener("click",this,false);
}
}
Object.defineProperty(myRect.prototype, "node", {
get: function(){ return this.SVGObj;}
});
Object.defineProperty(myRect.prototype, "CenterPoint", {
get: function(){
var self = this.SVGObj;
self.bbox = self.getBoundingClientRect(); // returned only after the item is drawn
self.Pc = {
x: self.bbox.left + self.bbox.width/2,
y: self.bbox.top + self.bbox.height/2
};
return self.Pc;
}
});
myRect.prototype.handleEvent= function(evt){
self = evt.target; // this returns the `rect` element
this.cntr = this.CenterPoint; // backup the origional center point Pc
this.r =5;
switch (evt.type){
case "click":
if (typeof self.moving == 'undefined' || self.moving == false) self.moving = true;
else self.moving = false;
if(self.moving == true){
self.move = setInterval(()=>this.animate(),100);
}
else{
clearInterval(self.move);
}
break;
default:
break;
}
}
myRect.prototype.step = function(x,y) {
return svg.createSVGTransformFromMatrix(svg.createSVGMatrix().translate(x,y));
}
myRect.prototype.rotate = function(r) {
return svg.createSVGTransformFromMatrix(svg.createSVGMatrix().rotate(r));
}
myRect.prototype.animate = function() {
self = this.SVGObj;
self.transform.baseVal.appendItem(this.step(this.cntr.x,this.cntr.y));
self.transform.baseVal.appendItem(this.rotate(this.r));
self.transform.baseVal.appendItem(this.step(-this.cntr.x,-this.cntr.y));
};
for (var i = 0; i < 10; i++) {
var x = Math.random() * 100,
y = Math.random() * 300;
var r= new myRect(x,y,10,10,'#'+Math.round(0xffffff * Math.random()).toString(16));
svg.appendChild(r.node);
}
UPDATE
I found the issue to be calculating the center point of the rect using the self.getBoundingClientRect() there is always 4px extra in each side, which means 8px extra in the width and 8px extra in the height, as well as both x and y are shifted by 4 px, I found this talking about the same, but neither setting self.setAttribute("display", "block"); or self.style.display = "block"; worked with me.
So, now I've one of 2 options, either:
Find a solution of the extra 4px in each side (i.e. 4px shifting of both x and y, and total 8px extra in both width and height),
or calculating the mid-point using:
self.Pc = {
x: self.x.baseVal.value + self.width.baseVal.value/2,
y: self.y.baseVal.value + self.height.baseVal.value/2
};
The second option (the other way of calculating the mid-point worked fine with me, as it is rect but if other shape is used, it is not the same way, I'll look for universal way to find the mid-point whatever the object is, i.e. looking for the first option, which is solving the self.getBoundingClientRect() issue.
Here we go…
FIDDLE
Some code for documentation here:
let SVG = ((root) => {
let ns = root.getAttribute('xmlns');
return {
e (tag) {
return document.createElementNS(ns, tag);
},
add (e) {
return root.appendChild(e)
},
matrix () {
return root.createSVGMatrix();
},
transform () {
return root.createSVGTransformFromMatrix(this.matrix());
}
}
})(document.querySelector('svg.stage'));
class Rectangle {
constructor (x,y,w,h) {
this.node = SVG.add(SVG.e('rect'));
this.node.x.baseVal.value = x;
this.node.y.baseVal.value = y;
this.node.width.baseVal.value = w;
this.node.height.baseVal.value = h;
this.node.transform.baseVal.initialize(SVG.transform());
}
rotate (gamma, x, y) {
let t = this.node.transform.baseVal.getItem(0),
m1 = SVG.matrix().translate(-x, -y),
m2 = SVG.matrix().rotate(gamma),
m3 = SVG.matrix().translate(x, y),
mtr = t.matrix.multiply(m3).multiply(m2).multiply(m1);
this.node.transform.baseVal.getItem(0).setMatrix(mtr);
}
}
Thanks #Philipp,
Solving catching the SVG center can be done, by either of the following ways:
Using .getBoundingClientRect() and adjusting the dimentions considering 4px are extra in each side, so the resulted numbers to be adjusted as:
BoxC = self.getBoundingClientRect();
Pc = {
x: (BoxC.left - 4) + (BoxC.width - 8)/2,
y: (BoxC.top - 4) + (BoxC.height - 8)/2
};
or by:
Catching the .(x/y).baseVal.value as:
Pc = {
x: self.x.baseVal.value + self.width.baseVal.value/2,
y: self.y.baseVal.value + self.height.baseVal.value/2
};
Below a full running code:
let ns="http://www.w3.org/2000/svg";
var root = document.createElementNS(ns, "svg");
root.style.width='100%';
root.style.height='100%';
root.style.backgroundColor = 'green';
document.body.appendChild(root);
//let SVG = function() {}; // let SVG = new Object(); //let SVG = {};
class SVG {};
SVG.matrix = (()=> { return root.createSVGMatrix(); });
SVG.transform = (()=> { return root.createSVGTransformFromMatrix(SVG.matrix()); });
SVG.translate = ((x,y)=> { return SVG.matrix().translate(x,y) });
SVG.rotate = ((r)=> { return SVG.matrix().rotate(r); });
class Rectangle {
constructor (x,y,w,h,fill) {
this.node = document.createElementNS(ns, 'rect');
self = this.node;
self.x.baseVal.value = x;
self.y.baseVal.value = y;
self.width.baseVal.value = w;
self.height.baseVal.value = h;
self.style.fill=fill;
self.transform.baseVal.initialize(SVG.transform()); // to generate transform list
this.transform = self.transform.baseVal.getItem(0), // to be able to read the matrix
this.node.addEventListener("click",this,false);
}
}
Object.defineProperty(Rectangle.prototype, "draw", {
get: function(){ return this.node;}
});
Object.defineProperty(Rectangle.prototype, "CenterPoint", {
get: function(){
var self = this.node;
self.bbox = self.getBoundingClientRect(); // There is 4px shift in each side
self.bboxC = {
x: (self.bbox.left - 4) + (self.bbox.width - 8)/2,
y: (self.bbox.top - 4) + (self.bbox.height - 8)/2
};
// another option is:
self.Pc = {
x: self.x.baseVal.value + self.width.baseVal.value/2,
y: self.y.baseVal.value + self.height.baseVal.value/2
};
return self.bboxC;
// return self.Pc; // will give same output of bboxC
}
});
Rectangle.prototype.animate = function () {
let move01 = SVG.translate(this.CenterPoint.x,this.CenterPoint.y),
move02 = SVG.rotate(10),
move03 = SVG.translate(-this.CenterPoint.x,-this.CenterPoint.y);
movement = this.transform.matrix.multiply(move01).multiply(move02).multiply(move03);
this.transform.setMatrix(movement);
}
Rectangle.prototype.handleEvent= function(evt){
self = evt.target; // this returns the `rect` element
switch (evt.type){
case "click":
if (typeof self.moving == 'undefined' || self.moving == false) self.moving = true;
else self.moving = false;
if(self.moving == true){
self.move = setInterval(()=>this.animate(),100);
}
else{
clearInterval(self.move);
}
break;
default:
break;
}
}
for (var i = 0; i < 10; i++) {
var x = Math.random() * 100,
y = Math.random() * 300;
var r= new Rectangle(x,y,10,10,'#'+Math.round(0xffffff * Math.random()).toString(16));
root.appendChild(r.draw);
}

HTML canvas measureText().width is too big

I try to find out the width of a text in a html canvas.
I'm using the measureText method but it gives me a value the is more than double as expected. I generate the Text by using the toSting method. If I just hard code the return from toSting into measureText it works fine...
console.log("--->width "+this.ctx.measureText("-100").width);
returns 22
console.log(labels[i]);
returns "-100"
console.log("->width "+this.ctx.measureText(labels[i]).width);
returns 48
Any ideas why?
thanks for help!
Here is the whole code: https://jsfiddle.net/falkinator/Lze1rnm5/4/
function createGraph(){
this.canvas = document.getElementById("graph");
this.ctx = this.canvas.getContext("2d");
this.options={};
this.datasets=[];
this.options.fontSize=11;
this.ctx.font=this.options.fontSize+"px Arial";
this.ctx.textAlign="left";
this.ctx.textBaseline="middle";
this.datasetLength=500;
this.dataset=function(options){
/*this.strokeColor=options.strokeColor;
this.signalName=options.signalName;
this.signalMin=options.signalMin;
this.signalMax=options.signalMax;
this.signalUnit=options.signalUnit;*/
this.data=[];
this.min;
this.max;
};
this.buildYLabels = function(scaleMin, scaleMax){
var labels = [];
var maxLabelWidth=0;
console.log("--->width "+this.ctx.measureText("-100").width);
for(i=10;i>=0;i--){
labels.push((scaleMin+((scaleMax-scaleMin)/10)*i).toString());
console.log((scaleMin+((scaleMax-scaleMin)/10)*i).toString());
console.log("->width "+this.ctx.measureText(labels[i]).width);
if(maxLabelWidth<this.ctx.measureText(labels[i]).width){
maxLabelWidth=this.ctx.measureText(labels[i]).width;
}
}
return {labels: labels,
maxLabelWidth: maxLabelWidth};
};
this.buildXLabels = function(x){
};
this.draw = function (){
var _this=this;
each(this.datasets,function(dataset, index){
//plot data
if(index>0)return;
//draw scale
var canvasHeight = _this.canvas.height;
console.log("canvas height="+canvasHeight);
var yLabels = _this.buildYLabels(-100, 500);
var currX = _this.options.fontSize/2;
var scaleHeight = canvasHeight-_this.options.fontSize*1.5;
var maxLabelWidth=yLabels.maxLabelWidth;
console.log(yLabels.maxLabelWidth);
each(yLabels.labels,function(label, index){
_this.ctx.fillText(label,0,currX);
console.log(label);
currX+=(scaleHeight/10);
});
_this.ctx.beginPath();
_this.ctx.moveTo(maxLabelWidth,0);
_this.ctx.lineTo(maxLabelWidth,canvasHeight);
_this.ctx.stroke();
});
};
this.addSignal = function(){
var dataset = new this.dataset({});
this.datasets.push(dataset);
};
this.pushData = function(data){
var _this=this;
if(data.length!=this.datasets.length){
console.error("the number of pushed data is diffrent to the number of datasets!");
return;
}
each(data,function(data, index){
_this.datasets[index].data.push(data);
if(_this.datasets[index].data.length>_this.datasetLength){
_this.datasets[index].data.shift();
}
});
};
this.calculateScaling = function(dataset){
var range = dataset.max - dataset.min;
var decStep = Math.pow(10,Math.floor(Math.log10(range)));
var scaleMin = roundTo(dataset.min/*+(decStep*10)/2*/, decStep);
var scaleMax = roundTo(dataset.max/*+(decStep*10)/2*/, decStep);
var scaleStep = (scaleMax - scaleMin)/10;
};
var minx=-34, maxx=424;
var range = maxx - minx;
var decStep = Math.pow(10, Math.floor(Math.log10(range)));
var scaleMin = roundTo(minx-(decStep/2), decStep);
var scaleMax = roundTo(maxx+(decStep/2), decStep);
var scaleStep = (scaleMax - scaleMin)/10;
console.log(this.buildYLabels(scaleMin,scaleMax));
console.log("range="+range);
console.log("log="+Math.floor(Math.log10(range)));
console.log("scaleStep="+scaleStep);
console.log("decStep="+decStep);
console.log("scaleMin="+scaleMin);
console.log("scaleMax="+scaleMax);
}
graph = new createGraph();
graph.addSignal();
graph.addSignal();
graph.addSignal();
graph.pushData([1,2,3]);
graph.pushData([1,2,3]);
graph.draw();
function each(array, callback){
console.log(callback);
for(i in array){
callback(array[i], i);
}
}
function roundTo(num, to){
return Math.round(num/to)*to;
}
<canvas id="graph"></canvas>
In your code that generates the labels, the loop index i is going from 10 to 0. Each time though the loop you are pushing a new label to the array (i.e. labels[0], labels[1], ...) but you are attempting to measure the labels using the loop index i (i.e. labels[10], labels[9], ...). Thus, the first few measurments are of the text "undefined".
Change...
console.log("->width "+this.ctx.measureText(labels[i]).width);
if(maxLabelWidth<this.ctx.measureText(labels[i]).width){
maxLabelWidth=this.ctx.measureText(labels[i]).width;
to...
console.log("->width "+this.ctx.measureText(labels[labels.length-1]).width);
if(maxLabelWidth<this.ctx.measureText(labels[labels.length-1]).width){
maxLabelWidth=this.ctx.measureText(labels[labels.length-1]).width;

Need help in displaying selection handles on rectangle using javascript

I am trying to add something to my code so as to select the image after drawing ( the selection handler should appear in the corners and in the middle of edge) and then drag or increase/decrease the height and width?
My sample code is in the fiddle , in this I am drawing a rectangle using the mouse event handlers. I want to select the rectangle and modify/alter it using the selection handlers instead of drawing it again.
Click the button ROI, metrics and then you can draw it using the mouse events.
http://jsfiddle.net/AhdJr/53/
var oImageBuffer = document.createElement('img');
var oCanvas=document.getElementById("SetupImageCanvas");
var o2DContext=oCanvas.getContext("2d");
var oRect = {};
var oROI = {};
var oMetrics ={};
var oLayers = new Array();
var bDragging = false;
var bSetROI = false;
var bSetLayers = false;
InitMouseEvents();
var oSelect = document.getElementById("ImageList");
oSelect.onchange=function() {
changeCanvasImage(oSelect[oSelect.selectedIndex].value);
}
// Canvas event handlers (listeners).
function InitMouseEvents() {
oCanvas.addEventListener('mousedown', MouseDownEvent, false);
oCanvas.addEventListener('mouseup', MouseUpEvent, false);
oCanvas.addEventListener('mousemove', MouseMoveEvent, false);
oCanvas.addEventListener('mouseout', MouseOutEvent, false);
}
function MouseDownEvent(e) {
oRect.startX = e.pageX - this.offsetLeft;
oRect.startY = e.pageY - this.offsetTop;
bDragging = true;
}
function MouseUpEvent() {
bDragging = false;
}
function MouseOutEvent() {
document.getElementById("MouseCoords").innerHTML="";
}
function MouseMoveEvent(e) {
if (bDragging) {
oRect.w = (e.pageX - this.offsetLeft) - oRect.startX;
oRect.h = (e.pageY - this.offsetTop) - oRect.startY;
oCanvas.getContext('2d').clearRect(0,0,oCanvas.width, oCanvas.height);
var oROI = document.getElementById("btnROI");
if (oROI.checked) {
SetROI();
}
var oLayer = document.getElementById("btnLAYER");
if (oLayer.checked) {
SetLayer();
}
var oMetrics = document.getElementById("btnMetrics");
if (oMetrics.checked) {
SetMetrics();
}
}
if (bSetROI) {
DrawROI();
}
if (bSetLayers) {
DrawLayers();
}
if(bSetMetrics){
DrawMetrics();
}
// Display the current mouse coordinates.
ShowCoordinates(e);
}
function ShowCoordinates(e) {
x=e.clientX;
y=e.clientY;
document.getElementById("MouseCoords").innerHTML="(" + x + "," + y + ") " + document.getElementById('txtPatchCount').value;
}
// Interactively draw ROI rectangle(s) on the canvas.
function SetROI() {
bSetROI = true;
oROI.startX = oRect.startX;
oROI.startY = oRect.startY;
oROI.w = oRect.w;
oROI.h = oRect.h;
}
function DrawROI() {
o2DContext.lineWidth=1.5;
o2DContext.strokeStyle = '#0F0';
o2DContext.strokeRect(oROI.startX, oROI.startY, oROI.w, oROI.h);
var iPatches = document.getElementById('txtPatchCount').value;
o2DContext.beginPath();
var iTop = oROI.startY;
var iBottom = oROI.startY + oROI.h;
var iLeft = oROI.startX;
var iX = iLeft;
for (var iPatch=1; iPatch<iPatches; ++iPatch) {
iX = iLeft + iPatch*oROI.w/iPatches;
o2DContext.moveTo(iX, iTop);
o2DContext.lineTo(iX, iBottom);
}
o2DContext.lineWidth=0.25;
o2DContext.stroke();
}
function SetMetrics() {
bSetMetrics = true;
oMetrics.startX = oRect.startX;
oMetrics.startY = oRect.startY;
oMetrics.w = oRect.w;
oMetrics.h = oRect.h;
}
function DrawMetrics(){
o2DContext.strokeStyle = 'black';
o2DContext.strokeRect(oMetrics.startX, oMetrics.startY, oMetrics.w, oMetrics.h);
o2DContext.beginPath();
var iTop = oMetrics.startY;
var iBottom = oMetrics.startY + oMetrics.h;
var iLeft = oMetrics.startX;
var iX = iLeft;
o2DContext.moveTo(iX, iTop);
o2DContext.lineTo(iX, iBottom);
o2DContext.stroke();
}
// Interactively draw layer boundaries on the canvas.
function SetLayer() {
bSetLayers = true;
oLayers.length = 0;
oLayers.push(oRect.startY);
oLayers.push(oRect.startY + oRect.h);
}
function DrawLayers() {
o2DContext.lineWidth=0.25;
o2DContext.strokeStyle = '#F00';
o2DContext.beginPath();
var iY = oLayers[0];
var iLeft = 0;
var iRight = oCanvas.width;
for (var iLayer=0; iLayer<oLayers.length; ++iLayer) {
iY = oLayers[iLayer];
o2DContext.moveTo(iLeft, iY);
o2DContext.lineTo(iRight, iY);
o2DContext.stroke();
}
}
The below blog is doing the same thing but I am not sure how to add this functionality in my code.
http://simonsarris.com/blog/225-canvas-selecting-resizing-shape
Please guide me how to add the same in mine.
Really appreciate the help.
try the following link.
It is doing somewhat you want to achieve.
http://simonsarris.com/blog/225-canvas-selecting-resizing-shape

Bind events to all elements in class instead of just to one id

I developed this interaction / script that scales whatever element is passed to it and if that element is pinched in on, it scales down / less.
This is how the script is initialised ( passing two arguments the container and the item to be scaled / transformed:
$(function(){
var zoom = new collapse('#zoom','#zoom :first');
var zoom2 = new collapse('#zoom2','#zoom2 :first');
var zoom3 = new collapse('#zoom3','#zoom3 :first');
});
It works fine as above on single IDs, but I need it to work on a class.
I tried this:
$(function(){
var zoom = new collapse('#zoom','.polaroid');
});
But that causes the whole script not to work because all the elements in that class are being passed instead of one as with an id.
This would only select the first item in the class so it won't work:
$(function(){
var zoom = new collapse('#zoom','.polaroid :first');
});
How can I change my script so that it is applied to all members of the .polaroid class in the #main container?
Here is my script:
function collapse(container, element){
container = $(container).hammer({
prevent_default: true,
scale_threshold: 0
});
element = $(element);
var displayWidth = container.width();
var displayHeight = container.height();
var MIN_ZOOM = 0;
var MAX_ZOOM = 1;
var scaleFactor = 1;
var previousScaleFactor = 1;
var startX = 0;
var startY = 0;
var translateX = 0;
var translateY = 0;
var previousTranslateX = 0;
var previousTranslateY = 0;
var time = 1;
var tch1 = 0,
tch2 = 0,
tcX = 0,
tcY = 0,
toX = 0,
toY = 0,
cssOrigin = "";
container.bind("transformstart", function(event){
e = event;
tch1 = [e.touches[0].x, e.touches[0].y],
tch2 = [e.touches[1].x, e.touches[1].y];
tcX = (tch1[0]+tch2[0])/2,
tcY = (tch1[1]+tch2[1])/2;
toX = tcX;
toY = tcY;
var left = $(element).offset().left;
var top = $(element).offset().top;
cssOrigin = (-(left) + toX)/scaleFactor +"px "+ (-(top) + toY)/scaleFactor +"px";
});
container.bind("transform", function(event){
scaleFactor = previousScaleFactor * event.scale;
scaleFactor = Math.max(MIN_ZOOM, Math.min(scaleFactor, MAX_ZOOM));
transform(event);
});
container.bind("transformend", function(event){
previousScaleFactor = scaleFactor;
if(scaleFactor > 0.42){
$(element).css('-webkit-transform', 'scaleY(1.0)').css('transform', 'scaleY(1.0)');
}
});
function transform(e){
var cssScale = "scaleY("+ scaleFactor +")";
element.css({
webkitTransform: cssScale,
webkitTransformOrigin: cssOrigin,
transform: cssScale,
transformOrigin: cssOrigin,
});
if(scaleFactor <= 0.42){
$(element).animate({height:0}, function(){
$(this).remove();
});
}
}
}
Wrap it as a jquery plugin:
$.fn.collapse = function(filter) {
return this.each(function(){
collapse(this,filter);
});
}
$("#zoom,#zoom1,#zoom2").collapse(".polaroid");
or if each of the zoom elements had a common class,
$(".zoomel").collapse(".polaroid");
You have to run collapse for each element.
element = $(element);
element.each(function(){
//each element would be this here
var $this= $(this);
//do whatever you want with $this
})

Categories

Resources