thanks in advance for any help you are able to give.
I have been tasked with sorting out the company website. I have made my way through the majority of it however have become stuck on a piece of JavaScript.
The site has a questionnaire with answers in three categories. From the score I plot a triangle. I have written a function which will return the calculations I want. As a test of this function I can write the calculated variables directly to a popup window.
I have created another function to then draw the triangle using CANVAS() in a popup. As a test to see if the new function works I put in the code to try and create the popup with the results in it. It goes as far as creating the pop up but does not write to it, as if the code stops after creating the popup. Can anyone tell me what I have done wrong?
Regards
Drew
Code:
<script type="text/javascript">
function myFunction()
{
function calcD()
{
var D1 = parseInt(document.forms.form1.elements.RadioGroup1.value);
var D2 = parseInt(document.forms.form1.elements.RadioGroup4.value);
var D3 = parseInt(document.forms.form1.elements.RadioGroup7.value);
var D4 = parseInt(document.forms.form1.elements.RadioGroup10.value);
var Ds = D1 + D2 + D3 + D4;
return Ds;
}
function calcI()
{
var I1 = parseInt(document.forms.form1.elements.RadioGroup2.value);
var I2 = parseInt(document.forms.form1.elements.RadioGroup5.value);
var I3 = parseInt(document.forms.form1.elements.RadioGroup8.value);
var I4 = parseInt(document.forms.form1.elements.RadioGroup11.value);
var Is = I1 + I2 + I3 + I4;
return Is;
}
function calcB()
{
var B1 = parseInt(document.forms.form1.elements.RadioGroup3.value);
var B2 = parseInt(document.forms.form1.elements.RadioGroup6.value);
var B3 = parseInt(document.forms.form1.elements.RadioGroup9.value);
var B4 = parseInt(document.forms.form1.elements.RadioGroup12.value);
var Bs = B1 + B2 + B3 + B4;
return Bs;
}
var X = 396.4;
var Y = 250;
var coS30 = 0.866025403784439;
var siN30m = -0.5;
var siN30p = 0.5;
var Dx = X;
var Dy = calcD() + Y;
var Bx = X - (calcB()*coS30);
var By = Y + (calcB()*siN30m);
var Ix = X + (calcI()*coS30);
var Iy = Y + (calcI()*siN30p);
var Xs = (Dx + Bx + Ix)/3;
var Ys = (Dy + By + Iy)/3;
/*
var myWindow1 = window.open("","MsgWindow","resizable,height=700,width=793");
myWindow1.document.write('var X = ' + X);
myWindow1.document.write('; var Y = ' + Y);
myWindow1.document.write('; var coS30 = ' + coS30);
myWindow1.document.write('; var siN30m = ' + siN30m);
myWindow1.document.write('; var siN30p = ' + siN30p);
myWindow1.document.write('; var Dx = ' + Dx);
myWindow1.document.write('; var Dy = ' + Dy);
myWindow1.document.write('; var Bx = ' + Bx);
myWindow1.document.write('; var By = ' + By);
myWindow1.document.write('; var Ix = ' + Ix);
myWindow1.document.write('; var Iy = ' + Iy);
myWindow1.document.write('; var Xs = ' + Xs);
myWindow1.document.write('; var Ys = ' + Ys);
myWindow1.document.close();
*/
}
</script>
<script type="text/javascript">
function draw() {
var myWindow1 = window.open("","MsgWindow","resizable,height=700,width=793");
myWindow1.document.write('var X = ' + X);
myWindow1.document.write('; var Y = ' + Y);
myWindow1.document.write('; var coS30 = ' + coS30);
myWindow1.document.write('; var siN30m = ' + siN30m);
myWindow1.document.write('; var siN30p = ' + siN30p);
myWindow1.document.write('; var Dx = ' + Dx);
myWindow1.document.write('; var Dy = ' + Dy);
myWindow1.document.write('; var Bx = ' + Bx);
myWindow1.document.write('; var By = ' + By);
myWindow1.document.write('; var Ix = ' + Ix);
myWindow1.document.write('; var Iy = ' + Iy);
myWindow1.document.write('; var Xs = ' + Xs);
myWindow1.document.write('; var Ys = ' + Ys);
myWindow1.document.close();
/*
var ctx = myWindow1.document.getElementById('canvas').getContext('2d');
var img = new Image();
img.onload = function() {
ctx.drawImage(img, 0, 0);
ctx.beginPath();
ctx.moveTo(Dx, Dy);
ctx.lineTo(Bx, By);
ctx.lineTo(Ix, Iy);
ctx.fill();
ctx.stroke();
};
img.src = "img/triangle.png";
*/
};
</script>
Variable values if you need them:
var X = 396.4;
var Y = 250;
var coS30 = 0.866025403784439;
var siN30m = -0.5;
var siN30p = 0.5;
var Dx = 396.4;
var Dy = 250;
var Bx = 396.4;
var By = 250;
var Ix = 396.4;
var Iy = 250;
var Xs = 396.3999999999999;
var Ys = 250;
Related
I want to make a function, that prints a width and height of an image
var a = 3;
var s = 2 * a;
var d = a * s;
print(d);
function cube(y) {
return y * y * y;
}
var g = cube(3);
print("g: " + g);
print("h: " + cube(99));
var img = new SimpleImage("drewRobert.png");
var imgN = img.setSize(75, 75);
print(img);
var t = new SimpleImage(25, 25);
print(t);
var img9 = new SimpleImage("drewRobert.png");
var img9N = img9.getPixel(77, 90);
print(img9N);
var img8N = img9.getGreen(0, 0);
print(img8N);
function alo(s, f, j) {
return s + f + j;
}
var sd = alo(9, 3, 1);
print(sd);
img5 = new SimpleImage("palm-and-beach.png");
//that'S one here
function printW(w) {
img5 = new SimpleImage("palm-and-beach.png");
return w = print(img5.getWidth());
}
print(printW(w));
<script src="https://www.dukelearntoprogram.com/course1/common/js/cs101/SimpleImage.js"></script>
I've been trying to make somekind of a starry sky. Here's the code.
When I'm trying to load the page, the console says that createHtmlElementFromStaris not defined. I can't find out why.
Thanks for your answers in advance!
var Star = function (x, y, look, color) {
var _x = x;
var _y = y;
var _look = look;
var _color = color;
this.createHtmlElementFromStar = function () {
var st = document.createElement("span");
st.style.position = "absolute";
st.style.left = x + "px";
st.style.top = (y - 10) + "px";
return st;
};
};
var Stars = function () {
var _stars = new Array();
this.createStars = function (look, count) {
var x = Math.random() * (400 - x) + x;
var y = Math.random() * (400 - y) + y;
var look = "";
var color = "#"+((1<<24)*Math.random()|0).toString(16);
_stars.push(new Star(x, y, look, color));
};
this.showStars = function () {
for (var i = 0; i < _stars.length; i++) {
document.body.appendChild(createHtmlElementFromStar(_stars[i]));
};
};};
var stars = new Stars();
stars.createStars(1, 50, "*", 150);
stars.showStars();
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 + ")";
...
}
}
I'm working on a Pixel Grid Canvas to draw stuff to in Javascript. I got everything running as it should, but only on Firefox, and it only works after refreshing the page.
My question is: Why does this only give the proper output after a refresh and what can I do to make it have the proper output on the first try.
function PixelGridCanvas(){
this.init = function(canvas, ps, gs, pc, gc){
this.ctx = canvas.getContext("2d");
this.pixelSize = ps;
this.gridSize = gs;
this.gridWidth = canvas.width/ps;
this.gridHeight = canvas.height/ps;
if(this.gridWidth <= 1) this.gridWidth = 1;
if(this.gridHeight <= 1) this.gridHeight = 1;
this.pixelColor = pc;
this.gridColor = gc;
};
this.clearCanvas = function(){
this.ctx.fillStyle = this.pixelColor;
this.ctx.fillRect(0,0, (this.gridWidth * this.pixelSize) - this.pixelSize, (this.gridHeight * this.pixelSize) - this.pixelSize);
this.ctx.fillStyle = this.gridColor;
var drawLine = false;
for(var i = 0; i < this.gridWidth * 2; i++){
if(drawLine) this.ctx.fillRect(i * this.pixelSize,0, this.pixelSize, ((this.gridHeight * this.pixelSize) * 2) + this.pixelSize);
drawLine = !drawLine;
}
var drawLine = false;
for(var i = 0; i < this.gridHeight * 2; i++){
if(drawLine) this.ctx.fillRect(0,i * this.pixelSize, ((this.gridWidth * this.pixelSize) * 2) - this.pixelSize, this.pixelSize);
drawLine = !drawLine;
}
};
this.drawImageAt = function(src, destx, desty){
console.log("drawImage");
var img = new Image();
img.src = src;
var icanvas = document.createElement('canvas');
icanvas.width = img.width;
icanvas.height = img.height;
var ictx = icanvas.getContext('2d');
ictx.drawImage(img, 0, 0, img.width, img.height);
for(var x = 0; x < icanvas.width; x++){
for(var y = 0; y < icanvas.height; y++){
//console.log("pixel");
var pixel = ictx.getImageData(x, y, 1, 1);
var data = pixel.data;
var rgba = 'rgba(' + data[0] + ',' + data[1] +
',' + data[2] + ',' + data[3] + ')';
this.ctx.fillStyle = rgba;
this.ctx.fillRect((destx * this.pixelSize) + (x * this.pixelSize) + (x * this.pixelSize), (desty * this.pixelSize) + (y * this.pixelSize) + (y * this.pixelSize), this.pixelSize, this.pixelSize);
}
}
};
this.drawImage = function(src){
this.drawImageAt(src,0,0);
};
}
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<script src="js/pgc/main.js"></script>
<script>
$( document ).ready(function() {
var c = document.getElementById("myCanvas");
var pgc = new PixelGridCanvas();
pgc.init(c, 2, 2, "#eeeeee", "#ffffff");
pgc.clearCanvas();
pgc.drawImage("imgs/test1.png");
pgc.drawImageAt("imgs/test1.png", 50,50);
});
</script>
</head>
<body>
<canvas id="myCanvas" width="320" height="320"></canvas>
</body>
</html>
Here's a link to it running on my personal site:
http://pgc.00ffff3.com/
edit:
enclosed the draw function in a onload for the image, but it still does the same thing. Am I understanding this wrong?
this.drawImageAt = function(src, destx, desty){
console.log("drawImage");
var img = new Image();
img.onload = function () {
var icanvas = document.createElement('canvas');
icanvas.width = img.width;
icanvas.height = img.height;
var ictx = icanvas.getContext('2d');
ictx.drawImage(img, 0, 0, img.width, img.height);
for(var x = 0; x < icanvas.width; x++){
for(var y = 0; y < icanvas.height; y++){
//console.log("pixel");
var pixel = ictx.getImageData(x, y, 1, 1);
var data = pixel.data;
var rgba = 'rgba(' + data[0] + ',' + data[1] +
',' + data[2] + ',' + data[3] + ')';
this.ctx.fillStyle = rgba;
this.ctx.fillRect((destx * this.pixelSize) + (x * this.pixelSize) + (x * this.pixelSize), (desty * this.pixelSize) + (y * this.pixelSize) + (y * this.pixelSize), this.pixelSize, this.pixelSize);
}
}
}
img.src = src;
};
The primary reason is because you image load is asynchronous so for your code to work your images must be loaded before you try to paint it. You can preload the images in JS and then on success of all the image loads fire the drawImageAt method.
I have the following javascript code that runs fine if called outside the jQuery function on the bottom. I don't know what I am doing wrong.
Bresenham Algorithm:
function bresenham(x0,y0,x1,y1){
var bresenham = [];
var x = 0;
var dx = x1-x0;
var dy = y1-y0;
var D = 2 * dy - dx;
bresenham.push(x0 + "," + y0);
var y = y0;
for (x = x0+1;x<=x1;x++){
if (D>0){
y = y+1;
bresenham.push(x + "," + y);
D = D + (2*dy - 2*dx);
} else {
bresenham.push(x + "," + y);
D = D + (2*dy);
}
}
return bresenham;
};
JQuery:
$(document).ready(function(){
$(".button").click(function(){
$("div#output p").remove();
var x0 = $('input[name=x0]').val();
var y0 = $('input[name=y0]').val();
var x1 = $('input[name=x1]').val();
var y1 = $('input[name=y1]').val();
var bres = bresenham(x0,y0,x1,y1);
console.log(bres);
});
});
If I input: x0 = 1, y = 0 and x1 = 15, y2 = 9
it outputs: ["1,0", "11,01", "12,01", "13,011", "14,0111", "15,0111"]
I would change
$(document).ready(function(){
$(".button").click(function(){
$("div#output p").remove();
var x0 = $('input[name=x0]').val();
var y0 = $('input[name=y0]').val();
var x1 = $('input[name=x1]').val();
var y1 = $('input[name=y1]').val();
var bres = bresenham(x0,y0,x1,y1);
console.log(bres);
});
});
to
$(document).ready(function(){
$(".button").click(function(){
$("div#output p").remove();
var x0 = parseInt($('input[name=x0]').val());
var y0 = parseInt($('input[name=y0]').val());
var x1 = parseInt($('input[name=x1]').val());
var y1 = parseInt($('input[name=y1]').val());
var bres = bresenham(x0,y0,x1,y1);
console.log(bres);
});
});