Trying to apply rotation, move and resize using mouse on SVG element. Here you can test this.
Currently I worked on South control, Center control and Rotate control.
Rotation works perfectly fine, I can rotate, stop and again rotate. But after I move the element by dragging center point, the rotation flickers first time and rotation starting point is different. I belive this is because center position is changed after translate. I tried recalculating center position but it did not work.
And scaling is moving the element instead of increasing the size.
Please help me on this. I am missing some adjustments here.
Note: First you have draw some path with mouse to get controls on it.
var svg = document.querySelector('.container');
var svgns = 'http://www.w3.org/2000/svg';
var path = document.createElementNS(svgns, 'path');
svg.appendChild(path);
var points = [];
var Resizer_Instance = null;
var boundingBox = svg.getBoundingClientRect();
var toSVGPath = function(points) {
var SVGPath = '';
for (var i = 0; i < points.length; i++) {
var prefix = (i == 0) ? 'M' : 'L';
SVGPath += prefix + points[i].x + ' ' + points[i].y + ' ';
}
return SVGPath;
};
var create_mousedown = false;
var createStart = function(event) {
create_mousedown = true;
};
var creating = function(event) {
if (create_mousedown) {
var point = svg.createSVGPoint();
point.x = event.clientX - boundingBox.left;
point.y = event.clientY - boundingBox.top;
var t = point.matrixTransform(svg.getScreenCTM().inverse());
points.push(t);
path.setAttributeNS(null, 'd', toSVGPath(points));
}
};
var createEnd = function(event) {
create_mousedown = true;
svg.removeEventListener('mousedown', createStart);
svg.removeEventListener('mousemove', creating);
svg.removeEventListener('mouseup', createEnd);
setTimeout(function functionName() {
Resizer_Instance = new Resizer(path, svg);
}, 500);
};
svg.addEventListener('mousedown', createStart);
svg.addEventListener('mousemove', creating);
svg.addEventListener('mouseup', createEnd);
var Resizer = (function() {
function Resizer(element) {
var that = this;
that.element = element;
createSelector.call(that);
document.addEventListener('mousemove', dragging);
document.addEventListener('mouseup', dragend);
}
var RAD2DEG = 180 / Math.PI;
function angleBetweenPoints(p1, p2) {
var angle = null;
if (p1.x == p2.x && p1.y == p2.y)
angle = Math.PI / 2;
else
angle = Math.atan2(p2.y - p1.y, p2.x - p1.x);
return (angle * RAD2DEG) + -90;
}
function controlPositions(el) {
var pt = svg.createSVGPoint();
var bbox = el.getBoundingClientRect();
var matrix = el.getScreenCTM().inverse();
var halfWidth = bbox.width / 2;
var halfHeight = bbox.height / 2;
var placements = {};
pt.x = bbox.left;
pt.y = bbox.top;
placements['nw'] = pt.matrixTransform(matrix);
pt.x += halfWidth;
placements['n'] = pt.matrixTransform(matrix);
pt.x += halfWidth;
placements['ne'] = pt.matrixTransform(matrix);
pt.y += halfHeight;
placements['e'] = pt.matrixTransform(matrix);
pt.y += halfHeight;
placements['se'] = pt.matrixTransform(svg.getScreenCTM().inverse());
pt.x -= halfWidth;
placements['s'] = pt.matrixTransform(matrix);
pt.x -= halfWidth;
placements['sw'] = pt.matrixTransform(matrix);
pt.y -= halfHeight;
placements['w'] = pt.matrixTransform(matrix);
pt.x += halfWidth;
placements['center'] = pt.matrixTransform(matrix);
pt.y -= (halfHeight + 30);
placements['rot'] = pt.matrixTransform(matrix);
return placements;
}
var dragging_element = null;
var dragstart = function(event) {
var box = this;
var context = box.context;
var rootContext = context.rootContext;
rootContext.current_handle_inaction = context.direction;
dragging_element = box;
};
var dragging = function(event) {
if (!dragging_element) return;
var box = dragging_element;
var context = box.context;
var rootContext = context.rootContext;
var currentHandle = rootContext.current_handle_inaction;
var control_points = rootContext.control_points;
if (currentHandle === context.direction) {
var point = svg.createSVGPoint();
point.x = event.clientX;
point.y = event.clientY;
var element = rootContext.element;
var transformed = point.matrixTransform(svg.getScreenCTM().inverse());
var centerPosition = context.center;
rootContext.angle = rootContext.angle || 0;
rootContext.hMove = rootContext.hMove || 0;
rootContext.vMove = rootContext.vMove || 0;
rootContext.scaleX = rootContext.scaleX || 1;
rootContext.scaleY = rootContext.scaleY || 1;
switch (currentHandle) {
case "rot":
rootContext.angle = angleBetweenPoints(transformed, centerPosition);
break;
case "center":
rootContext.hMove = transformed.x - centerPosition.x;
rootContext.vMove = transformed.y - centerPosition.y;
break;
case "s":
var startPos = control_points[currentHandle];
var vMove = transformed.y - startPos.y;
rootContext.scaleY += (vMove > 0 ? -1 : 1) * 0.001;
break;
}
var move_transform = "translate(" + rootContext.hMove + " " + rootContext.vMove + ")";
var rotate_transform = "rotate(" + rootContext.angle + ", " + centerPosition.x + ", " + centerPosition.y + ")";
var scale_transform = "scale(" + rootContext.scaleX + ", " + rootContext.scaleY + ")";
var transform = [move_transform, rotate_transform, scale_transform].join(' ');
rootContext.element.setAttribute('transform', transform);
rootContext.controlGroup.setAttribute('transform', transform);
}
};
var dragend = function() {
if (!dragging_element) return;
var box = dragging_element;
var context = box.context;
var rootContext = context.rootContext;
delete rootContext.current_handle_inaction;
// createSelector.call(rootContext);
dragging_element = null;
};
var adjustPositions = function() {
var that = this;
var control_points = that.control_points;
var controlGroup = that.controlGroup;
var point = svg.createSVGPoint();
for (var direction in control_points) {
var dP = control_points[direction];
point.x = dP.x;
point.y = dP.y;
debugger;
control_points[direction] = point.matrixTransform(controlGroup.getScreenCTM().inverse());
}
return control_points;
};
var Deg2Rad = 0.017453292519943295;
var createSelector = function() {
var that = this;
var points = that.control_points;
if (points) {
points = adjustPositions.call(that);
} else {
points = controlPositions(that.element, svg);
}
that.control_points = points;
var existingBoxes = {};
var controlGroup = that.controlGroup;
if (!controlGroup) {
controlGroup = document.createElementNS(svgns, 'g');
that.controlGroup = controlGroup;
svg.appendChild(controlGroup);
}
that.control_boxes = that.control_boxes || {};
var line_name = "connecting-line",
line_element = that.control_boxes['connecting-line'];
var line_route = ["nw", "n", "rot", 'n', "ne", "e", "se", "s", "sw", "w", "nw"];
if (!line_element) {
line_element = document.createElementNS(svgns, 'path');
line_element.style.cssText = "fill: none; stroke: #f41542; opacity: 0.5";
that.control_boxes[line_name] = line_element;
controlGroup.appendChild(line_element);
var pathString = "";
line_route.forEach(function(direction) {
var point = points[direction];
var command = pathString.length === 0 ? "M" : " L ";
pathString += (command + point.x + " " + point.y);
});
line_element.setAttribute('d', pathString);
}
Object.keys(points).forEach(function(direction) {
var point = points[direction];
var box = that.control_boxes[direction];
if (!box) {
box = document.createElementNS(svgns, 'circle');
box.style.cssText = "fill: #5AABAB";
that.control_boxes[direction] = box;
box.setAttributeNS(null, 'r', 3);
box.setAttribute('handle', direction);
box.addEventListener('mousedown', dragstart.bind(box));
controlGroup.appendChild(box);
}
box.setAttributeNS(null, 'cx', point.x);
box.setAttributeNS(null, 'cy', point.y);
box.context = {
point: point,
direction: direction,
rootContext: that,
center: points.center
};
});
};
var prototype = {
constructor: Resizer
};
Resizer.prototype = prototype;
return Resizer;
})();
path {
fill: none;
stroke: #42B6DF;
}
body,
html {
height: 100%;
width: 100%;
margin: 0;
}
<svg class="container" version="1.1" baseProfile="full" style="position:absolute;left:0;top:0;height:100%;width:100%;-ms-transform:scale(1,1);transform:scale(1,1);-webkit-transform:scale(1,1);-moz-transform:scale(1,1);-o-transform:scale(1,1);transform:scale(1,1);-ms-transform-origin:0, 0;-webkit-transform-origin:0, 0;-moz-transform-origin:0, 0;-o-transform-origin:0, 0;transform-origin:0, 0"
viewBox="-220.38356461849224 6442.3347962008365 454.7376658611161 114.54981723871151"></svg>
You can't easily handle all three transform operations (translate, scale and rotate) with just those three transform functions alone. You actually should use four functions.
You should remember the original centre point of the element. Let's call this ocx and ocy. Then do the following:
translate the original centre point to the origin
perform the scale
perform the rotation
translate the centre back to the new (current) centre position.
So the transform string would look something like this:
transform="translate(ncx,ncy) rotate(rot) scale(sx,sy) translate(-ocx,-ocy)"
This way you can keep all the operations isolated, and you don't need to alter the others when one changes.
You are currently calculating angle in relation to the initial center of the figure (the one when you have just drawn it). This is wrong - you need to calculate angle in relation to the center of the figure after previous move.
Fiddle
I've stripped the parts that I didn't change.
var dragging = function(event) {
...
if (currentHandle === context.direction) {
...
var initialCenterPosition = context.center,
// use the coordinates saved after last move or
// initial coordinates if there are none saved
previousCenterPosition = rootContext.previousCenterPosition || initialCenterPosition;
...
switch (currentHandle) {
case "rot":
rootContext.angle = angleBetweenPoints(transformed, previousCenterPosition);
break;
case "center":
rootContext.hMove = transformed.x - initialCenterPosition.x;
rootContext.vMove = transformed.y - initialCenterPosition.y;
// remember the new center coordinates
rootContext.previousCenterPosition = {
x: transformed.x,
y: transformed.y
};
break;
case "s":
...
}
var move_transform = "translate(" + rootContext.hMove + " " + rootContext.vMove + ")";
var rotate_transform = "rotate(" + rootContext.angle + ", " + initialCenterPosition.x + ", " + initialCenterPosition.y + ")";
var scale_transform = "scale(" + rootContext.scaleX + ", " + rootContext.scaleY + ")";
...
}
}
Related
I have the code listed below. The code is on https://omegalords.ga/test.world.html. I want the item to not move beyond the canvas. How can I find how many units are in the canvas? I am aware of the other errors in the console. I specifically need the canvas's dimensions in reference to items placed on the canvas. The point of the code is to create a wolf and a deer that interact. The problem is that I need to ensure that the 2 don't leave the canvas.
<script src=../script/algebra-0.2.6.min.js></script>
<canvas id="myCanvas" style="width:100%; height:100%;">
</canvas>
<script>
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
console.log(document.body.style)
var findDis = function(x1,y1,x2,y2){
//Finds distance rounded to the nearest 1000th
return Math.trunc(((Math.sqrt((x1-x2) * (x1-x2) + (y1-y2) * (y1-y2)))*1000))/1000
}
var findIntersections = function(b,a,m,r){
var Fraction = algebra.Fraction;
var Expression = algebra.Expression;
var Equation = algebra.Equation;
var coords = {
l:[],
g:[]
}
//b^2 - 2bx + x^2 - 2bm^2x + b^2m^2 - r^2
var sl = algebra.parse(Math.pow(b,2)+" - "+2*b+"x + x^2 + "+Math.pow(m,2)+"x^2 -" + 2 * b * Math.pow(m,2) + "* x + " + Math.pow(b,2) * Math.pow(m,2) + " - " + Math.pow(r,2));
var sr = algebra.parse("0")
var eq = new Equation(sl, sr);
//Solves for x rounded to the nearest 1000
coords.l.push(Math.trunc((eq.solveFor("x")[0]*1000))/1000);
coords.g.push(Math.trunc((eq.solveFor("x")[1]*1000))/1000);
//Solves for y
coords.l.push(Math.trunc((eq.solveFor("x")[0] * m + a - (b * m))*1000)/1000);
coords.g.push(Math.trunc((eq.solveFor("x")[1] * m + a - (b * m))*1000)/1000);
return JSON.stringify(coords);
}
var findSlope = function(x1,y1,x2,y2){
//Finds Slope rounded to the nearest 1000th
return Math.trunc(((y1-y2)/(x1-x2))*1000)/1000;
}
var getRandomInt = function(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min)) + min;
}
var wolves = [];
var deers = [];
var animal = function(x,y){
this.age = 0
this.strength = 0;
this.x = x;
this.y = y;
this.hp = 100;
this.size = 10;
this.hunger = 0;
}
animal.prototype.move = function(){
this.nearbyPredators = [];
this.nearbyPrey = [];
for(var j = 0;j<this.predatorTypes.length;j++){
for(var i = 0;i < this.predatorTypes[j].length;i++){
if(findDis(this.predatorTypes[j][i].x,this.predatorTypes[j][i].y,this.x,this.y) < 40){
this.nearbyPredators.push(this.predatorTypes[j][i]);
}else{
console.log(findDis(this.predatorTypes[j][i].x,this.this.predatorTypes[j][i].y,this.x,this.y))
}
}
}
//finds all nearby prey
for(var j = 0;j<this.preyTypes.length;j++){
for(var i = 0;i < this.preyTypes[j].length;i++){
if(findDis(this.preyTypes[j][i].x,this.preyTypes[j][i].y,this.x,this.y) < 40){
this.nearbyPrey.push(this.preyTypes[j][i]);
}else{
console.log(findDis(this.preyTypes[j][i].x,this.preyTypes[j][i].y,this.x,this.y))
}
}
}
if(this.nearbyPredators.length == 0){
//If there are no nearby prey, move randomly
if(this.nearbyPrey.length === 0){
var tx = this.x + getRandomInt(-8,9);
var ty = this.y + getRandomInt(-9,8);
while(!(tx > (0 + this.size)) && !(ty > (0 + this.size)) && !(tx < (canvas.length - this.size)) && !(ty < (canvas.height - this.size))){
tx = this.x + getRandomInt(-8,9);
ty = this.y + getRandomInt(-9,8);
}
this.x = tx
this.y = ty
//If there is only one nearby prey, move towards it
}else if(this.nearbyPrey.length === 1){
this.nearestPrey = this.nearbyPrey[0]
var tempDis = findDis(this.x,this.y,this.nearestPrey.x,this.nearestPrey.y);
if(tempDis < 2*this.nearestPrey.size){
this.bite(this.nearestPrey)
}else {
var slope = findSlope(this.nearestPrey.x,this.nearestPrey.y,this.x,this.y);
var coords = JSON.parse(findIntersections(this.x,this.y,slope,0.125));
var ldis = findDis(this.x,this.y,coords.l[0],coords.l[1]);
var gdis = findDis(this.x,this.y,coords.g[0],coords.g[1]);
if(ldis > gdis){
this.x = coords.l[0]
this.y = coords.l[1]
}else {
this.x = coords.g[0]
this.y = coords.g[1]
}
}
//If there is more than 1, find the nearest prey and move towards it
}else {
for(var i = 0; i < this.nearbyPrey.length; i++){
this.tempDis = getDis(this.x,this.y,this.nearbyPrey[i].x,this.nearbyPrey[i].y)
if(typeof this.nearestPrey == 'undefined'){
this.nearestPrey = {
prey:this.nearbyPrey[i],
distance:this.tempDis
}
this.tempDis = undefined
}else {
if(this.tempDis > this.nearestPrey.distance){
this.nearestPrey = {
prey:this.nearbyPrey[i],
distance:this.tempDis
}
}
}
}
var slope = findSlope(this.nearestPrey.x,this.nearestPrey.y,this.x,this.y)
var coords = JSON.parse(findIntersections(this.nearestPrey.x,this.nearestPrey.y,slope,0.25));
var ldis = findDis(this.nearestPrey.x,this.nearestPrey.y,coords.l[0],coords.l[1]);
var gdis = findDis(this.nearestPrey.x,this.nearestPrey.y,coords.g[0],coords.g[1]);
if(ldis > gdis){
this.x = coords.l[0]
this.y = coords.l[1]
}else {
this.x = coords.g[0]
this.y = coords.g[1]
}
}
}else {
}
}
var grass = function(){
}
var deer = function(x,y){
animal.call(this,x,y)
deers.push(this);
this.preyTypes = [grass];
this.predatorTypes = [wolves];
}
var wolf = function(x,y){
animal.call(this,x,y)
wolves.push(this);
this.predatorTypes = [];
this.preyTypes = [deers]
}
deer.prototype = Object.create(animal.prototype);
wolf.prototype = Object.create(animal.prototype);
wolf.prototype.bite = function(prey){
prey.hp -= this.strength;
if(prey.hp < 0){
prey.die()
}
this.hunger += 40/100
console.log(this.hunger);
console.log(prey.hp)
}
new wolf(100,100)
new deer(50,50);
var init = function(){
ctx.translate(0.5, 0.5);
ctx.lineWidth = .5
window.setInterval(draw,250);
}
var draw = function(){
ctx.clearRect(0,0,canvas.width,canvas.height)
wolves[0].move();
for(var i=0;i<wolves.length;i++){
ctx.beginPath()
ctx.arc(wolves[i].x,wolves[i].y,10,0,2*Math.PI);
ctx.stroke();
}
for(var i=0; i<deers.length;i++){
ctx.beginPath();
ctx.arc(deers[i].x,deers[i].y,10,0,2*Math.PI);
ctx.stroke();
}
}
init()
</script>
var canvasHeight = canvas.clientHeight;
var canvasWidth = canvas.clientWidth;
Please note, this will also include any padding, but by default, the canvas has no padding.
Sources:
https://developer.mozilla.org/en-US/docs/Web/API/Element/clientHeight
https://developer.mozilla.org/en-US/docs/Web/API/Element/clientWidth
You can get the css properties:
var canvasWidth = canvas.style.width;
var canvasHeight = canvas.style.height;
On website https://omegalords.ga/world/test.html, I have a code that calculates 1 unit towards a target. In the code the slope is 1. so the x and y of the next spot to jump to should be the same. Why does it at some point change and the 2 coordinates. I have ran the numbers, but it doesn't work properly. Could someone explain hwy?
</canvas>
<script>
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
var findDis = function(x1,y1,x2,y2){
//Finds distance rounded to the nearest 1000th
return Math.trunc(((Math.sqrt((x1-x2) * (x1-x2) + (y1-y2) * (y1-y2)))*1000))/1000
}
var findIntersections = function(b,a,m,r){
var Fraction = algebra.Fraction;
var Expression = algebra.Expression;
var Equation = algebra.Equation;
var coords = {
l:[],
g:[]
}
//b^2 - 2bx + x^2 - 2bm^2x + b^2m^2 - r^2
var sl = algebra.parse(Math.pow(b,2)+" - "+2*b+"x + x^2 + "+Math.pow(m,2)+"x^2 -" + 2 * b * Math.pow(m,2) + "* x + " + Math.pow(b,2) * Math.pow(m,2) + " - " + Math.pow(r,2));
var sr = algebra.parse("0")
var eq = new Equation(sl, sr);
//Solves for x rounded to the nearest 1000
coords.l.push(Math.trunc((eq.solveFor("x")[0]*1000))/1000);
coords.g.push(Math.trunc((eq.solveFor("x")[1]*1000))/1000);
//Solves for y
coords.l.push(Math.trunc((coords.l[0] * m + a - (b * m))*1000)/1000);
coords.g.push(Math.trunc((coords.g[0] * m + a - (b * m))*1000)/1000);
return JSON.stringify(coords);
}
var findSlope = function(x1,y1,x2,y2){
//Finds Slope rounded to the nearest 1000th
return Math.trunc(((y1-y2)/(x1-x2))*1000)/1000;
}
var getRandomInt = function(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min)) + min;
}
var wolves = [];
var deers = [];
var deer = function(x,y){
this.x = x;
this.y = y;
this.hp = 100;
this.size = 10;
this.hunger = 0*%;
this.preyTypes = [grass];
this.predatorTypes = [wolves];
deers.push(this);
}
var wolf = function(x,y){
this.x = x;
this.y = y;
this.hp = 100;
this.size = 10;
this.hunger = 0 * %;
wolves.push(this);
this.preyTypes = [deers]
}
wolf.prototype.move = function(){
this.nearbyPredators = [];
this.nearbyPrey = [];
//finds all nearby prey
for(var j = 0;j<this.preyTypes.length;j++){
for(var i = 0;i < this.preyTypes[j].length;i++){
if(findDis(this.preyTypes[j][i].x,this.preyTypes[j][i].y,this.x,this.y) < 40){
this.nearbyPrey.push(this.preyTypes[j][i]);
}else{
console.log(findDis(this.preyTypes[j][i].x,this.preyTypes[j][i].y,this.x,this.y))
}
}
}
//If there are no nearby prey, move randomly
if(this.nearbyPrey.length === 0){
wolf.x += getRandomInt(-8,9)
wolf.y -= getRandomInt(-9,8);
//If there is only one nearby prey, move towards it
}else if(this.nearbyPrey.length === 1){
this.nearestPrey = this.nearbyPrey[0]
var slope = findSlope(this.nearestPrey.x,this.nearestPrey.y,this.x,this.y);
console.log(slope);
var coords = JSON.parse(findIntersections(this.x,this.y,slope,1));
console.log(coords);
var ldis = findDis(this.x,this.y,coords.l[0],coords.l[1]);
var gdis = findDis(this.x,this.y,coords.g[0],coords.g[1]);
console.log(ldis,gdis)
if(ldis > gdis){
this.x = coords.l[0]
this.y = coords.l[1]
console.log(this.x,this.y)
}else {
this.x = coords.g[0]
this.y = coords.g[1]
console.log(this.x,this.y)
}
//If there is more than 1, find the nearest prey and move towards it
}else {
for(var i = 0; i < this.nearbyPrey.length; i++){
this.tempDis = getDis(this.x,this.y,this.nearbyPrey[i].x,this.nearbyPrey[i].y)
if(typeof this.nearestPrey == 'undefined'){
this.nearestPrey = {
prey:this.nearbyPrey[i],
distance:this.tempDis
}
this.tempDis = undefined
}else {
if(this.tempDis > this.nearestPrey.distance){
this.nearestPrey = {
prey:this.nearbyPrey[i],
distance:this.tempDis
}
}
}
}
var slope = findSlope(this.nearestPrey.x,this.nearestPrey.y,this.x,this.y)
var coords = JSON.parse(findIntersections(this.nearestPrey.x,this.nearestPrey.y,slope,1));
var ldis = findDis(this.nearestPrey.x,this.nearestPrey.y,coords.l[0],coords.l[1]);
var gdis = findDis(this.nearestPrey.x,this.nearestPrey.y,coords.g[0],coords.g[1]);
if(ldis > gdis){
this.x = coords.l[0]
this.y = coords.l[1]
}else {
this.x = coords.g[0]
this.y = coords.g[1]
}
}
}
wolf.prototype.bite = function(prey){
prey.hp -= this.strength;
this.hunger += 40 * %
console.log(this.hunger);
console.log(this.nearestPrey.hp)
}
new wolf(100,100)
new deer(80,80);
var init = function(){
ctx.translate(0.5, 0.5);
ctx.lineWidth = .5
window.setInterval(draw,1000);
}
var draw = function(){
ctx.clearRect(0,0,canvas.width,canvas.height)
wolves[0].move();
for(var i=0;i<wolves.length;i++){
ctx.beginPath();
ctx.arc(deers[0].x,deers[0].y,10,0,2*Math.PI);
ctx.stroke();
ctx.beginPath()
ctx.arc(wolves[i].x,wolves[i].y,10,0,2*Math.PI);
ctx.stroke();
}
}
init()
</script>
I want to have a function that draws a box in the coordinates x and y.
I can't find a guide that doesn't answer more/less than what i want.
Thank's in advance.
I wrote this script some time ago so there may be ways to update it, but the idea is to get the position of the cursor onmousedown and attach an onmousemove listener. Each time you move the mouse you adjust th size of the box based on the position. Then on mouseup you remove the onmousemove listener.
https://jsfiddle.net/47nmp90w/
dragBox = (function() {
var _curX;
var _curY;
var _workingEl;
var _docEl = document.documentElement;
if (_docEl.scrollTop === 0) {
var testDocEl = _docEl.scrollTop;
_docEl.scrollTop++;
_docEl = testDocEl+1 === _docEl.scrollTop-- ? _docEl : document.body;
}
return {
drag: function(e) {
var evt = e ? e : window.event;
_width = Math.abs(_curX - evt.clientX);
_height = Math.abs(_curY - evt.clientY);
if (evt.shiftKey) {
var minDimension = Math.min(_width, _height) + 'px';
_workingEl.style.width = minDimension;
_workingEl.style.height = minDimension;
} else {
_workingEl.style.width = _width + 'px';
_workingEl.style.height = _height + 'px';
}
_workingEl.style.left = Math.min(_curX, evt.clientX) + _docEl.scrollLeft + 'px';
_workingEl.style.top = Math.min(_curY, evt.clientY) + _docEl.scrollTop + 'px';
},
draw: function(e) {
var evt = e ? e : window.event;
if (evt.which === 1) {
_curX = evt.clientX;
_curY = evt.clientY;
_workingEl = document.createElement('div');
_workingEl.className = 'drawing';
document.body.appendChild(_workingEl);
window.onmousemove = dragBox.drag;
window.onmouseup = function() {
window.onmousemove = null;
_workingEl.className = 'done';
_workingEl = false;
}
}
}
};
})();
window.onmousedown = dragBox.draw;
Edit
Here is how you would create a box with a set a data. You just set height and width styles, then give it a left position equal to your x coordinate and a top position of your y coordinate.
https://jsfiddle.net/RDay/47nmp90w/4/
var createButton = document.getElementById('create');
var xPosInput = document.getElementById('x-pos');
var yPosInput = document.getElementById('y-pos');
var widthInput = document.getElementById('width');
var heightInput = document.getElementById('height');
var target = document.getElementById('target');
createButton.onclick = function() {
var xPos = xPosInput.value;
var yPos = yPosInput.value;
var width = widthInput.value;
var height = heightInput.value;
var box = document.createElement('div');
box.className = 'box';
box.style.left = xPos + 'px';
box.style.top = yPos + 'px';
box.style.width = width + 'px';
box.style.height = height + 'px';
box.style.left = xPos + 'px';
target.appendChild(box);
};
I have multiple charts generated by PHPChart but when i use from print option to print the chart in pdf, and png in chrome it is not working for bar chart types but work for line chart, but if there is one bar chart it works, in Firefox it is not working for vertical bar chart but work for horizontal bar chart.
all type of charts are generated dynamically using database data there is no difference in case of html wrapper tags.
when i click on export button browser hung up.
The javascript code:
function getImageData(obj, type, title)
{
var str;
imgtype = type;
if (type == 'jpg-pdf')
{
imgtype = 'jpg';
type = 'pdf';
}
var imgCanvas = $('#'+obj).jqplotToImageCanvas();
if (imgCanvas) {
str = imgCanvas.toDataURL("image/"+imgtype);
}
else {
str = null;
}
$('#pngdata').val(str);
$('#imgtype').val(type);
$('#imgtitle').val(title);
$('#imgform').submit();
}
and the jqplot function
$.fn.jqplotToImageCanvas = function(options) {
options = options || {};
var x_offset = (options.x_offset == null) ? 0 : options.x_offset;
var y_offset = (options.y_offset == null) ? 0 : options.y_offset;
var backgroundColor = (options.backgroundColor == null) ? 'rgb(255,255,255)' : options.backgroundColor;
if ($(this).width() == 0 || $(this).height() == 0) {
return null;
}
// excanvas and hence IE < 9 do not support toDataURL and cannot export images.
if ($.jqplot.use_excanvas) {
return null;
}
var newCanvas = document.createElement("canvas");
var h = $(this).outerHeight(true);
var w = $(this).outerWidth(true);
var offs = $(this).offset();
var plotleft = offs.left;
var plottop = offs.top;
var transx = 0, transy = 0;
// have to check if any elements are hanging outside of plot area before rendering,
// since changing width of canvas will erase canvas.
var clses = ['jqplot-table-legend', 'jqplot-xaxis-tick', 'jqplot-x2axis-tick', 'jqplot-yaxis-tick', 'jqplot-y2axis-tick', 'jqplot-y3axis-tick',
'jqplot-y4axis-tick', 'jqplot-y5axis-tick', 'jqplot-y6axis-tick', 'jqplot-y7axis-tick', 'jqplot-y8axis-tick', 'jqplot-y9axis-tick',
'jqplot-xaxis-label', 'jqplot-x2axis-label', 'jqplot-yaxis-label', 'jqplot-y2axis-label', 'jqplot-y3axis-label', 'jqplot-y4axis-label',
'jqplot-y5axis-label', 'jqplot-y6axis-label', 'jqplot-y7axis-label', 'jqplot-y8axis-label', 'jqplot-y9axis-label' ];
var temptop, templeft, tempbottom, tempright;
for (var i = 0, j = clses.length; i < j; i++) {
$(this).find('.'+clses[i]).each(function() {
temptop = $(this).offset().top - plottop;
templeft = $(this).offset().left - plotleft;
tempright = templeft + $(this).outerWidth(true) + transx;
tempbottom = temptop + $(this).outerHeight(true) + transy;
if (templeft < -transx) {
w = w - transx - templeft;
transx = -templeft;
}
if (temptop < -transy) {
h = h - transy - temptop;
transy = - temptop;
}
if (tempright > w) {
w = tempright;
}
if (tempbottom > h) {
h = tempbottom;
}
});
}
newCanvas.width = w + Number(x_offset);
newCanvas.height = h + Number(y_offset);
var newContext = newCanvas.getContext("2d");
newContext.save();
newContext.fillStyle = backgroundColor;
newContext.fillRect(0,0, newCanvas.width, newCanvas.height);
newContext.restore();
newContext.translate(transx, transy);
newContext.textAlign = 'left';
newContext.textBaseline = 'top';
function getLineheight(el) {
var lineheight = parseInt($(el).css('line-height'), 10);
if (isNaN(lineheight)) {
lineheight = parseInt($(el).css('font-size'), 10) * 1.2;
}
return lineheight;
}
function writeWrappedText (el, context, text, left, top, canvasWidth) {
var lineheight = getLineheight(el);
var tagwidth = $(el).innerWidth();
var tagheight = $(el).innerHeight();
var words = text.split(/\s+/);
var wl = words.length;
var w = '';
var breaks = [];
var temptop = top;
var templeft = left;
for (var i=0; i<wl; i++) {
w += words[i];
if (context.measureText(w).width > tagwidth && w.length > words[i].length) {
breaks.push(i);
w = '';
i--;
}
}
if (breaks.length === 0) {
// center text if necessary
if ($(el).css('textAlign') === 'center') {
templeft = left + (canvasWidth - context.measureText(w).width)/2 - transx;
}
context.fillText(text, templeft, top);
}
else {
w = words.slice(0, breaks[0]).join(' ');
// center text if necessary
if ($(el).css('textAlign') === 'center') {
templeft = left + (canvasWidth - context.measureText(w).width)/2 - transx;
}
context.fillText(w, templeft, temptop);
temptop += lineheight;
for (var i=1, l=breaks.length; i<l; i++) {
w = words.slice(breaks[i-1], breaks[i]).join(' ');
// center text if necessary
if ($(el).css('textAlign') === 'center') {
templeft = left + (canvasWidth - context.measureText(w).width)/2 - transx;
}
context.fillText(w, templeft, temptop);
temptop += lineheight;
}
w = words.slice(breaks[i-1], words.length).join(' ');
// center text if necessary
if ($(el).css('textAlign') === 'center') {
templeft = left + (canvasWidth - context.measureText(w).width)/2 - transx;
}
context.fillText(w, templeft, temptop);
}
}
function _jqpToImage(el, x_offset, y_offset) {
var tagname = el.tagName.toLowerCase();
var p = $(el).position();
var css = window.getComputedStyle ? window.getComputedStyle(el, "") : el.currentStyle; // for IE < 9
var left = x_offset + p.left + parseInt(css.marginLeft, 10) + parseInt(css.borderLeftWidth, 10) + parseInt(css.paddingLeft, 10);
var top = y_offset + p.top + parseInt(css.marginTop, 10) + parseInt(css.borderTopWidth, 10)+ parseInt(css.paddingTop, 10);
var w = newCanvas.width;
// var left = x_offset + p.left + $(el).css('marginLeft') + $(el).css('borderLeftWidth')
// somehow in here, for divs within divs, the width of the inner div should be used instead of the canvas.
if ((tagname == 'div' || tagname == 'span') && !$(el).hasClass('jqplot-highlighter-tooltip')) {
$(el).children().each(function() {
_jqpToImage(this, left, top);
});
var text = $(el).jqplotChildText();
if (text) {
newContext.font = $(el).jqplotGetComputedFontStyle();
newContext.fillStyle = $(el).css('color');
writeWrappedText(el, newContext, text, left, top, w);
}
}
// handle the standard table legend
else if (tagname === 'table' && $(el).hasClass('jqplot-table-legend')) {
newContext.strokeStyle = $(el).css('border-top-color');
newContext.fillStyle = $(el).css('background-color');
newContext.fillRect(left, top, $(el).innerWidth(), $(el).innerHeight());
if (parseInt($(el).css('border-top-width'), 10) > 0) {
newContext.strokeRect(left, top, $(el).innerWidth(), $(el).innerHeight());
}
// find all the swatches
$(el).find('div.jqplot-table-legend-swatch-outline').each(function() {
// get the first div and stroke it
var elem = $(this);
newContext.strokeStyle = elem.css('border-top-color');
var l = left + elem.position().left;
var t = top + elem.position().top;
newContext.strokeRect(l, t, elem.innerWidth(), elem.innerHeight());
// now fill the swatch
l += parseInt(elem.css('padding-left'), 10);
t += parseInt(elem.css('padding-top'), 10);
var h = elem.innerHeight() - 2 * parseInt(elem.css('padding-top'), 10);
var w = elem.innerWidth() - 2 * parseInt(elem.css('padding-left'), 10);
var swatch = elem.children('div.jqplot-table-legend-swatch');
newContext.fillStyle = swatch.css('background-color');
newContext.fillRect(l, t, w, h);
});
// now add text
$(el).find('td.jqplot-table-legend-label').each(function(){
var elem = $(this);
var l = left + elem.position().left;
var t = top + elem.position().top + parseInt(elem.css('padding-top'), 10);
newContext.font = elem.jqplotGetComputedFontStyle();
newContext.fillStyle = elem.css('color');
writeWrappedText(elem, newContext, elem.text(), l, t, w);
});
var elem = null;
}
else if (tagname == 'canvas') {
newContext.drawImage(el, left, top);
}
}
$(this).children().each(function() {
_jqpToImage(this, x_offset, y_offset);
});
return newCanvas;
};
kindly help me.
I want to add 4 text boxes which will give me the coordinates of a rectangle and if I manually edit the coordinates it should change /alter the rectangle as well.
Please tell me how to proceed with this solution.
In my example if you click ROI it will draw a rectangle I want the upper and lower X and Y coordinates of the same.
the working fiddle is http://jsfiddle.net/qf6Ub/2/
// references to canvas and context
var oImageBuffer = document.createElement('img');
var oCanvas = document.getElementById("SetupImageCanvas");
var o2DContext = oCanvas.getContext("2d");
// set default context states
o2DContext.lineWidth = 1;
o2DContext.translate(0.50, 0.50); // anti-aliasing trick for sharper lines
// vars to save user drawings
var layers = [];
var currentColor = "black";
// vars for dragging
var bDragging = false;
var startX, startY;
// vars for user-selected status
var $roiCheckbox = document.getElementById("btnROI");
var $layersCheckbox = document.getElementById("btnLAYER");
var $patches = document.getElementById('txtPatchCount');
var $mouse = document.getElementById("MouseCoords");
var roiIsChecked = false;
var layersIsChecked = false;
var patchCount = 0;
// listen for mouse events
oCanvas.addEventListener('mousedown', MouseDownEvent, false);
oCanvas.addEventListener('mouseup', MouseUpEvent, false);
oCanvas.addEventListener('mousemove', MouseMoveEvent, false);
oCanvas.addEventListener('mouseout', MouseOutEvent, false);
$("#txtPatchCount").keyup(function () {
getStatus();
// clear the canvas
o2DContext.clearRect(0, 0, oCanvas.width, oCanvas.height);
// redraw all previously saved line-pairs and roi
for (var i = 0; i < layers.length; i++) {
var layer = layers[i];
if (layer.patchCount > 0) {
layer.patchCount = patchCount;
}
draw(layer);
}
});
// mouse event handlers
function MouseDownEvent(e) {
e.preventDefault();
startX = e.clientX - this.offsetLeft;
startY = e.clientY - this.offsetTop;
currentColor = randomColor();
getStatus();
bDragging = true;
}
function MouseUpEvent(e) {
if (!bDragging) {
return;
}
e.preventDefault();
bDragging = false;
mouseX = e.clientX - this.offsetLeft;
mouseY = e.clientY - this.offsetTop;
layers.push({
x1: startX,
y1: startY,
x2: mouseX,
y2: mouseY,
color: currentColor,
drawLayer: layersIsChecked,
patchCount: patchCount,
});
}
function MouseOutEvent(e) {
MouseUpEvent(e);
}
function MouseMoveEvent(e) {
if (!bDragging) {
return;
}
var mouseX = e.clientX - this.offsetLeft;
var mouseY = e.clientY - this.offsetTop;
// clear the canvas
o2DContext.clearRect(0, 0, oCanvas.width, oCanvas.height);
// redraw all previously saved line-pairs and roi
for (var i = 0; i < layers.length; i++) {
draw(layers[i]);
}
// create a temporary layer+roi object
var tempLayer = {
x1: startX,
y1: startY,
x2: mouseX,
y2: mouseY,
color: currentColor,
drawLayer: layersIsChecked,
patchCount: patchCount,
};
// draw the temporary layer+roi object
draw(tempLayer);
// Display the current mouse coordinates.
$mouse.innerHTML = "(" + mouseX + "," + mouseY + ")" + patchCount;
}
function draw(layer) {
if (layer.drawLayer) {
// set context state
o2DContext.lineWidth = 0.50;
o2DContext.strokeStyle = layer.color;
// draw parallel lines
hline(layer.y1);
hline(layer.y2);
}
if (layer.patchCount > 0) {
// set context state
o2DContext.lineWidth = 1.5;
o2DContext.strokeStyle = '#0F0';
// draw regions
o2DContext.strokeRect(layer.x1, layer.y1, (layer.x2 - layer.x1), (layer.y2 - layer.y1));
var w = layer.x2 - layer.x1;
o2DContext.beginPath();
for (var i = 1; i < layer.patchCount; i++) {
var x = layer.x1 + i * w / layer.patchCount;
o2DContext.moveTo(x, layer.y1);
o2DContext.lineTo(x, layer.y2);
}
o2DContext.stroke();
}
}
function getStatus() {
roiIsChecked = $roiCheckbox.checked;
layersIsChecked = $layersCheckbox.checked;
patchCount = $patches.value;
if (!roiIsChecked || !patchCount) {
patchCount = 0;
}
}
function randomColor() {
return ('#' + Math.floor(Math.random() * 16777215).toString(16));
}
function hline(y) {
o2DContext.beginPath();
o2DContext.moveTo(0, y);
o2DContext.lineTo(oCanvas.width, y);
o2DContext.stroke();
}
document.getElementById("MouseCoords").innerHTML = "(" + x + "," + y + "); "
+"("+ oPixel.x + "," + oPixel.y + "); "
+"("+ oCanvasRect.left + "," + oCanvasRect.top + ")";
}
Ok, I went back to the drawing board and came up with this FIDDLE.
It provides the dimensions of the div and its location from the top and left of the container.
You can calculate the exact coordinates from those numbers.
JS
var divwidth = $('.coord').width();
var divheight = $('.coord').height();
var pos = $('.coord').offset();
$('#divdimensions').html(divwidth + ',' + divheight);
$('#divposition').html( pos.left + ',' + pos.top );