Canvas window.addEvent error when running on gh-pages - javascript

I have a HTML5 canvas project which allows for the uploading of an image to the canvas. Then it is variously drawn on.
I can run this project locally with
$ http-server
Running this locally, I don't get any errors.
The project is on github
The issue is that in gh-pages I get the error,
Uncaught TypeError: window.addEvent is not a function
at (index):22
Line 22 is,
window.addEvent('load', function() {
This is also a problem when trying to run this with the snippet tool.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/tether/1.4.0/js/tether.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" crossorigin="anonymous">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/js/bootstrap.min.js" crossorigin="anonymous"></script>
<script src="https://rawgit.com/eligrey/FileSaver.js/master/FileSaver.js"></script>
<script src="https://rawgit.com/eligrey/canvas-toBlob.js/master/canvas-toBlob.js"></script>
<script type="text/javascript">
var Pts = [];
var dist;
let inputValue;
var ratio;
var angle;
window.addEvent('load', function() {
var imageLoader = document.getElementById('imageLoader');
imageLoader.addEventListener('change', handleImage, false);
var c = document.getElementById('canvas');
var ctx = c.getContext('2d');
function handleImage(e) {
var reader = new FileReader();
reader.onload = function(event) {
var img = new Image();
img.onload = function() {
c.width = img.width;
c.height = img.height;
ctx.drawImage(img, 0, 0);
}
img.src = event.target.result;
}
reader.readAsDataURL(e.target.files[0]);
}
$("#canvas").click(function(e) {
getPosition(e);
});
});
var pointSize = 3;
// Event will be a click event which can be retrieved as first parameter in the addEventListener(function(event){}); or in jQuery with $("selector").click(function(event){});
function getPosition(event) {
var rect = canvas.getBoundingClientRect();
var x = event.clientX - rect.left; // x == the location of the click in the document - the location (relative to the left) of the canvas in the document
var y = event.clientY - rect.top; // y == the location of the click in the document - the location (relative to the top) of the canvas in the document
Pts.push({
x: x,
y: y
});
if (Pts.length == 2) {
dist = getDistance();
addInput(Pts[1].x, Pts[1].y);
}
drawCoordinates(x, y);
if (Pts.length % 2 == 0) {
drawLine(Pts[Pts.length - 2].x, Pts[Pts.length - 2].y, Pts[Pts.length - 1].x, Pts[Pts.length - 1].y);
};
}
function decimalAdjust(type, value, exp) {
// If the exp is undefined or zero...
if (typeof exp === 'undefined' || +exp === 0) {
return Math[type](value);
}
value = +value;
exp = +exp;
// If the value is not a number or the exp is not an integer...
if (isNaN(value) || !(typeof exp === 'number' && exp % 1 === 0)) {
return NaN;
}
// If the value is negative...
if (value < 0) {
return -decimalAdjust(type, -value, exp);
}
// Shift
value = value.toString().split('e');
value = Math[type](+(value[0] + 'e' + (value[1] ? (+value[1] - exp) : -exp)));
// Shift back
value = value.toString().split('e');
return +(value[0] + 'e' + (value[1] ? (+value[1] + exp) : exp));
}
// Decimal round
if (!Math.round10) {
Math.round10 = function(value, exp) {
return decimalAdjust('round', value, exp);
};
}
function getDistance() {
dist = Math.sqrt(Math.pow(Math.abs(Pts[Pts.length - 2].x - Pts[Pts.length - 1].x), 2) + Math.pow(Math.abs(Pts[Pts.length - 2].y - Pts[Pts.length - 1].y), 2));
return dist.toFixed(2);
}
function drawLine(x1, y1, x2, y2) {
var ctx = document.getElementById("canvas").getContext("2d");
ctx.beginPath();
ctx.moveTo(x1, y1);
ctx.lineTo(x2, y2);
if (Pts.length < 3) {
ctx.strokeStyle = 'blue';
} else {
ctx.strokeStyle = 'black';
}
ctx.stroke();
dist = getDistance();
txt = dist * ratio;
if (Pts.length > 2) {
drawText(txt, x1, y1, x2, y2);
}
}
function addInput(x, y) {
var input = document.createElement('input');
input.type = 'text';
input.style.position = 'fixed';
input.style.left = (x + 4) + 'px';
input.style.top = (y + 4) + 'px';
input.onkeydown = handleEnter;
document.body.appendChild(input);
input.focus();
hasInput = true;
}
function handleEnter(e) {
var keyCode = e.keyCode;
if (keyCode === 13) {
inputValue = this.value;
document.body.removeChild(this);
hasInput = false;
ratio = inputValue / dist;
if (Pts.length == 2) {
drawText("reference line = " + dist * ratio, Pts[Pts.length - 2].x, Pts[Pts.length - 2].y, Pts[Pts.length - 1].x, Pts[Pts.length - 1].y);
}
}
}
function drawCoordinates(x, y) {
var pointSize = 3; // Change according to the size of the point.
var ctx = document.getElementById("canvas").getContext("2d");
if (Pts.length < 3) {
ctx.fillStyle = "blue"; // Red color
} else {
ctx.fillStyle = "red"; // Red color
}
ctx.beginPath(); //Start path
ctx.arc(x, y, pointSize, 0, Math.PI * 2, true); // Draw a point using the arc function of the canvas with a point structure.
ctx.fill(); // Close the path and fill.
}
function drawText(txt, x1, y1, x2, y2) {
// (x,y) coordinate of text mid way between both points
x = ((x2 + x1) / 2) + 5;
y = ((y2 + y1) / 2) + 5;
var ctx = document.getElementById("canvas").getContext("2d");
ctx.save();
ctx.textBaseline = 'top';
ctx.textAlign = 'left';
// ctx.font = font;
angle = Math.atan((Math.abs(y2 - y1)) / (Math.abs(x2 - x1)));
console.log(angle);
ctx.translate(x, y)
// ctx.rotate(-1 * angle);
ctx.fillText(txt, 0, 0);
ctx.restore();
}
function download_image() {
// Dump the canvas contents to a file.
var canvas = document.getElementById("canvas");
var today = new Date();
var date = today.getFullYear() + "" + (today.getMonth() + 1) + "" + "" + today.getDate() + "" + (today.getHours() - 2) + "" + today.getMinutes() + "" + today.getSeconds();
today.getDate();
canvas.toBlob(function(blob) {
saveAs(blob, date + "Canvas.png");
}, "image/png");
};
</script>
</head>
<style media="screen">
upload_form {
background-color: red;
width: 100%;
padding: 20px;
}
</style>
<body>
<div class="container">
<div class="row">
<div class="col-md-12 upload_form">
<label>Image File:</label><br/>
<input type="file" id="imageLoader" name="imageLoader" />
<button type="button" onclick="download_image()" name="button">Save Canvas</button>
</div>
</div>
<div class=row>
<div class="col-md-12">
<canvas id="canvas"></canvas>
</div>
</div>
</div>
</body>
</html>
Any help would be greatly appreciated,
Thanks

I'm not sure why it works with http-server, but you should probably be using window.addEventListener instead of window.addEvent

Related

How to click one circle among others in canvas using JavaScript

I want to click each circle separately from an array of circles. Because I want to do different tasks for each circle after being clicked. Though multiple circles are stored inside the array circles[] when I am clicking on the circles the alert is not showing without one circle and it's showing the alert 5 times. I am assuming that is the last circle which has been drawn randomly and only this circle has the click effect!
Can someone please help me to figure this out?
const canvas = document.getElementById('flower');
const ctx = canvas.getContext('2d');
var offsetX = canvas.offsetLeft;
var offsetY = canvas.offsetTop;
var circles = [];
function main(){
if (typeof document !== 'undefined') {
var r = 20;
for (var j=0; j<5; j++){
var cx = random()*(canvas.width);
var cy = random()*(canvas.height);
var r = 25;
var color = "rgb(" + Math.floor(random() * 256) + "," + Math.floor(random() * 256)
+ "," + Math.floor(random() * 256) + ")";
ctx.beginPath();
ctx.arc(cx, cy, r, 0, 2 * Math.PI);
ctx.fillStyle = color;
ctx.fill();
ctx.closePath();
var obj = {};
obj['x'] = cx;
obj['y'] = cy;
circles.push(obj);
}
//console.log(circles); 5 circles are stored in circles[]
circles.forEach(function(entry){
canvas.addEventListener('click', function(e) {
var clickX = e.clientX - offsetX;
var clickY = e.clientY - offsetY;
var dx = cx - clickX;
var dy = cy - clickY;
if (dx * dx + dy * dy <= r * r) {
alert("you are inside the circle");
}
});
});
}
}
var seed = 1;
function random() {
var x = Math.sin(seed++) * 10000;
return x - Math.floor(x);
}
main();
html, body, div {
width: 100%;
height: 100%;
margin: 0;
}
<body>
<div id="design">
<canvas id="flower"></canvas>
</div>
</body>
To achieve expected result, use below option of using isPointInPath method to detect click of canvas shape
Use Path2D constructor to draw circle
const circle = new Path2D();
circle.arc(cx, cy, r, 0, 2 * Math.PI);
ctx.fillStyle = color;
ctx.fill(circle);
Use below click event Listener
canvas.addEventListener("click", function(event) {
if (ctx.isPointInPath(circle, event.clientX, event.clientY)) {
alert("you are inside the circle");
}
});
Please refer this link for more details on https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/isPointInPath
Sample working code for reference
const canvas = document.getElementById("flower");
const ctx = canvas.getContext("2d");
var offsetX = canvas.offsetLeft;
var offsetY = canvas.offsetTop;
var circles = [];
function main() {
if (typeof document !== "undefined") {
var r = 20;
for (var j = 0; j < 5; j++) {
var cx = random() * canvas.width;
var cy = random() * canvas.height;
var r = 25;
var color =
"rgb(" +
Math.floor(random() * 256) +
"," +
Math.floor(random() * 256) +
"," +
Math.floor(random() * 256) +
")";
const circle = new Path2D();
circle.arc(cx, cy, r, 0, 2 * Math.PI);
ctx.fillStyle = color;
ctx.fill(circle);
canvas.addEventListener("click", function(event) {
if (ctx.isPointInPath(circle, event.clientX, event.clientY)) {
alert("you are inside the circle");
}
});
}
}
}
var seed = 1;
function random() {
var x = Math.sin(seed++) * 10000;
return x - Math.floor(x);
}
main();
html, body, div {
width: 100%;
height: 100%;
margin: 0;
}
<body>
<div id="design">
<canvas id="flower"></canvas>
</div>
</body>
Codepen - https://codepen.io/nagasai/pen/NWWNmdj

detecting a click inside a hexagon drawn using canvas?

I'm working on a certain layout where I need to draw a hexagon which needs to be clickable. I'm using the Path2D construct and isPointInPath function. I'm constructing an animation where a number of hexagons is created and then each moved to a certain position. After the movement is done, I am attaching onclick event handlers to certain hexagons. However there is weird behaviour.
Some initialized variables
const COLOR_DARK = "#73b6c6";
const COLOR_LIGHT = "#c3dadd";
const COLOR_PRIMARY = "#39a4c9";
const TYPE_PRIMARY = 'primary';
let hexagons = [];
Below is the function which draws the hexagons.
function drawHex(ctx, x, y, hexProps, stroke, color) {
let myPath = new Path2D();
myPath.moveTo(x + hexProps.width*0.5, y);
myPath.lineTo(x, y + hexProps.height*hexProps.facShort);
myPath.lineTo(x, y + hexProps.height*hexProps.facLong);
myPath.lineTo(x + hexProps.width*0.5, y + hexProps.height);
myPath.lineTo(x + hexProps.width, y + hexProps.height*hexProps.facLong);
myPath.lineTo(x + hexProps.width, y + hexProps.height*hexProps.facShort);
myPath.lineTo(x + hexProps.width*0.5, y);
myPath.closePath();
if (stroke){
ctx.strokeStyle = color;
ctx.stroke(myPath);
} else {
ctx.fillStyle = color;
ctx.fill(myPath);
}
return myPath;
}
This function populates the hexagon array
function populateLeftHex(canvasWidth, canvasHeight, hexProps) {
const startX = canvasWidth / 2;
const startY = canvasHeight / 2;
const baseLeft = canvasWidth * 0.05;
for(let i = 0; i < 5; i++){
let hexNumber = (i % 4 == 0)? 2: 1;
for(let j = 0; j < hexNumber; j++){
hexagons.push({
startX: startX,
startY: startY,
endX: baseLeft + (2 * j) + ((i % 2 == 0)? (hexProps.width * j) : (hexProps.width/2)),
endY: ((i + 1) * hexProps.height) - ((i) * hexProps.height * hexProps.facShort) + (i* 2),
stroke: true,
color: ( i % 2 == 0 && j % 2 == 0)? COLOR_DARK : COLOR_LIGHT,
type: TYPE_PRIMARY
});
}
}
}
And here is where Im calling the isPointInPath function.
window.onload = function (){
const c = document.getElementById('canvas');
const canvasWidth = c.width = window.innerWidth,
canvasHeight = c.height = window.innerHeight,
ctx = c.getContext('2d');
window.requestAnimFrame = (function (callback) {
return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame || function (callback) {
window.setTimeout(callback, 1000 / 60);
};
})();
console.log(canvasWidth);
let hexProps = {
width: canvasWidth * 0.075,
get height () {
return this.width/Math.sqrt(3) + (1.5)*(this.width/Math.sqrt(2)/2);
} ,
facShort: 0.225,
get facLong () {
return 1 - this.facShort;
}
};
populateLeftHex(canvasWidth, canvasHeight, hexProps);
let pct = 0;
const fps = 200;
animate();
function animate () {
setTimeout(function () {
// increment pct towards 100%
pct += .03;
// if we're not done, request another animation frame
if (pct < 1.00) {
requestAnimFrame(animate);
} else { //if pct is no longer less than 1.00, then the movement animation is over.
hexagons.forEach(function (hex) {
if(hex.type === TYPE_PRIMARY) {
console.info(hex.path);
c.onclick = function(e) {
let x = e.clientX - c.offsetLeft,
y = e.clientY - c.offsetTop;
console.info(ctx.isPointInPath(hex.path, (e.clientX - c.offsetLeft), (e.clientY - c.offsetTop) ));
};
}
})
}
ctx.clearRect(0, 0, c.width, c.height);
// draw all hexagons
for ( let i = 0; i < hexagons.length; i++) {
// get reference to next shape
let hex = hexagons[i];
// note: dx/dy are fixed values
// they could be put in the shape object for efficiency
let dx = hex.endX - hex.startX;
let dy = hex.endY - hex.startY;
let nextX = hex.startX + dx * pct;
let nextY = hex.startY + dy * pct;
hex = hexagons[i];
ctx.fillStyle = hex.color;
hex.path = drawHex(ctx, nextX, nextY, hexProps, hex.stroke, hex.color);
}
}, 1000 / fps);
}
Can you help me figure out what I'm doing wrong? Maybe I misunderstood how Path2D works? Thanks in advance.
Had to do a bit of work to build a test page as your example is incomplete, but this is working for me - though my hexagon is concave...
var myCanvas = document.getElementById("myCanvas");
var ctx = myCanvas.getContext("2d");
var hexProps = {width:100, height:100, facShort:-2, facLong:10};
var hexagons = [];
function drawHex(ctx, x, y, hexProps, stroke, color) {
let myPath = new Path2D();
myPath.moveTo(x + hexProps.width*0.5, y);
myPath.lineTo(x, y + hexProps.height*hexProps.facShort);
myPath.lineTo(x, y + hexProps.height*hexProps.facLong);
myPath.lineTo(x + hexProps.width*0.5, y + hexProps.height);
myPath.lineTo(x + hexProps.width, y + hexProps.height*hexProps.facLong);
myPath.lineTo(x + hexProps.width, y + hexProps.height*hexProps.facShort);
myPath.lineTo(x + hexProps.width*0.5, y);
myPath.closePath();
if (stroke){
ctx.strokeStyle = color;
ctx.stroke(myPath);
} else {
ctx.fillStyle = color;
ctx.fill(myPath);
}
return myPath;
}
hexagons.push({type:0, path:drawHex(ctx,100,100,hexProps,false,"#0f0")});
hexagons.forEach(function (hex) {
if(hex.type === 0) {
console.info(hex.path);
myCanvas.onclick = function(e) {
let x = e.clientX - myCanvas.offsetLeft,
y = e.clientY - myCanvas.offsetTop;
console.info(x,y);
console.info(ctx.isPointInPath(hex.path, (e.clientX -
myCanvas.offsetLeft), (e.clientY - myCanvas.offsetTop) ));
};
}
})
<canvas width=500 height=500 id=myCanvas style='border:1px solid red'></canvas>
Test clicks give true and false where expected:
test.htm:48 165 168
test.htm:49 true
test.htm:48 151 336
test.htm:49 false
test.htm:48 124 314
test.htm:49 true
test.htm:48 87 311
test.htm:49 false

slow script in the first 3 executions

i made a simple script for color a pixel and all the near pixel with the same color
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script src="http://code.jquery.com/jquery-latest.js"></script>
<title>
Click foto
</title>
<style type="text/css">
/*<![CDATA[*/
html, body{
height: 100%;
}
/*]]>*/
</style>
</head>
<body>
<div id="canvasDiv">
</div>
</body>
<script>
var canvasDiv = document.getElementById('canvasDiv');
canvas = document.createElement('canvas');
canvas.setAttribute('width', 500);
canvas.setAttribute('height', 500);
canvas.setAttribute('id', 'canvas');
$(canvasDiv).prepend(canvas);
if(typeof G_vmlCanvasManager != 'undefined') {
canvas = G_vmlCanvasManager.initElement(canvas);
}
var context = canvas.getContext('2d');
var imageObj = new Image();
imageObj.onload = function() {
$(canvas).attr({width : this.width, height: this.height});
context.drawImage(imageObj,0,0);
};
imageObj.src = 'cartina_italia.png';
$('#canvas').click(function(e){
console.time('click');
mouseX = e.pageX - this.offsetLeft;
mouseY = e.pageY - this.offsetTop;
c = this.getContext('2d');
p = c.getImageData(mouseX, mouseY, 1, 1).data;
hex = ("000000" + rgbToHex(p[0], p[1], p[2])).slice(-6);
console.timeEnd('click');
console.time('selectArea');
selectArea(mouseX,mouseY,c,hex);
console.timeEnd('selectArea');
});
function selectArea(x,y,c,color){
if (x>=0 && y>=0){
p = c.getImageData(x, y, 1, 1).data;
hex =("000000" + rgbToHex(p[0], p[1], p[2])).slice(-6);
if (color==hex){
c.fillStyle = "rgba(255,0,0,0.1)";
c.fillRect( x, y, 1, 1 );
selectArea(x+1,y,c,color);
selectArea(x-1,y,c,color);
selectArea(x,y+1,c,color);
selectArea(x,y-1,c,color);
}
}
}
function rgbToHex(r, g, b) {
if (r > 255 || g > 255 || b > 255)
throw "Invalid color component";
return ((r << 16) | (g << 8) | b).toString(16);
}
</script>
</html>
i'm using for test this file: http://mappa.italiachecambia.org/assets/homemap/cartina_italia.png the first 3 times i click on a region for color it i have a slow response(1000-5000ms), after the first 3 times the function end in 50ms
i can't use jsfiddle for show the problem bc i get cross-origin error
the code is simple recursive function that change the color of the clicked pixel and launched on the near pixel untill the pixel color is different from the first
but i don't understand why the first 3 times have this slow response and after the 4th is with 0 lag....
You should cache the imageData of the hole image and work with that data instead of invoking getImageData on each selectArea call. Also you could think of implementing it iterative, to prevent maximum call stack errors.
Here's an example:
var ExtendedCanvas = (function() {
var context, data, canvas;
function ExtendedCanvas(selector, imageSrc) {
var wrapper = document.querySelector(selector);
this.element = canvas = document.createElement('canvas');
context = this.element.getContext('2d');
loadImage.call(this, imageSrc, function(image) {
canvas.setAttribute('width', image.width);
canvas.setAttribute('height', image.height);
context.drawImage(image,0,0);
data = context.getImageData(0,0,canvas.width, canvas.height);
});
wrapper.appendChild(this.element);
}
function loadImage(src, cb) {
var image = new Image();
var canvas = this.element;
image.onload = function() {
cb(this);
}
image.crossOrigin = 'Anonymous';
image.src = src;
}
ExtendedCanvas.prototype.getPixelIndex = function(x, y) {
return (Math.floor(y) * canvas.width + Math.floor(x)) * 4;
}
ExtendedCanvas.prototype.getPixelColor = function(x, y) {
var index = this.getPixelIndex(x, y);
var d = data.data;
var r = d[index];
var g = d[index + 1];
var b = d[index + 2];
var a = d[index + 3];
return [r, g, b, a];
}
ExtendedCanvas.prototype.setPixelColor = function(x, y, color) {
var index = this.getPixelIndex(x, y);
var d = data.data;
d[index] = color[0];
d[index + 1] = color[1];
d[index + 2] = color[2];
d[index + 3] = color[3];
}
ExtendedCanvas.prototype.fill = function(x, y, fillColor) {
if(x < 0 || y < 0 || x > canvas.width || y > canvas.height) {
return;
}
fillColor = fillColor || [0,0,0,255];
var stack = [];
var color = this.getPixelColor(x, y).join();
if(color === fillColor) {
return;
}
stack.push([x, y]);
context.fillStyle = fillColor;
if(color === fillColor.join()) {
return;
}
while(stack.length > 0) {
var position = stack.pop();
var posX = position[0];
var posY = position[1];
var posColor = this.getPixelColor(posX, posY).join();
if(posColor === color) {
this.setPixelColor(posX, posY, fillColor);
stack.push([posX, posY + 1]);
stack.push([posX, posY - 1]);
stack.push([posX + 1, posY]);
stack.push([posX - 1, posY]);
}
}
context.putImageData(data, 0, 0);
}
return ExtendedCanvas;
})();
document.addEventListener('DOMContentLoaded', function() {
var c = new ExtendedCanvas('#canvasWrapper', 'https://i.imgur.com/QWaKVGO.png');
c.element.addEventListener('click', function(e) {
var x = e.pageX - this.offsetLeft;
var y = e.pageY - this.offsetTop;
c.fill(x, y);
});
});
<div id="canvasWrapper"></div>

Incorrectly drawing line to edge of ellipse given angle

Sorry for the confusing title, I don't know how to succinctly describe my question.
I'm drawing an ellipse on a canvas element using javascript and I'm trying to figure out how to detect if the mouse is clicked inside of the ellipse or not. The way I'm trying to do this is by comparing the distance from the center of the ellipse to the mouse to the radius of the ellipse at the same angle as the mouse click. Here's a terrible picture representing what I just said if it's still confusing:
Obviously this isn't working, otherwise I wouldn't be asking this, so below is a picture of the computed radius line (in red) and the mouse line (in blue). In this picture, the mouse has been clicked at a 45° angle to the center of the ellipse and I've calculated that the radius line is being drawn at about a 34.99° angle.
And below is the calculation code:
//This would be the blue line in the picture above
var mouseToCenterDistance = distanceTo(centerX, centerY, mouseX, mouseY);
var angle = Math.acos((mouseX - centerX) / mouseToCenterDistance);
var radiusPointX = (radiusX * Math.cos(angle)) + centerX;
var radiusPointY = (radiusY * Math.sin(-angle)) + centerY;
//This would be the red line in the picture above
var radius = distanceTo(centerX, centerY, radiusPointX, radiusPointY);
var clickedInside = mouseToCenterDistance <= radius;
I'm really not sure why this isn't working, I've been staring at this math forever and it seems correct. Is it correct and there's something about drawing on the canvas that's making it not work? Please help!
Ellipse line intercept
Finding the intercept includes solving if the point is inside.
If it is the ellipse draw via the 2D context the solution is as follows
// defines the ellipse
var cx = 100; // center
var cy = 100;
var r1 = 20; // radius 1
var r2 = 100; // radius 2
var ang = 1; // angle in radians
// rendered with
ctx.beginPath();
ctx.ellipse(cx,cy,r1,r2,ang,0,Math.PI * 2,true)
ctx.stroke()
To find the point on the ellipse that intersects the line from the center to x,y. To solve I normalise the ellipse so that it is a circle (well the line is moved so that the ellipse is a circle in its coordinate space).
var x = 200;
var y = 200;
var ratio = r1 / r2; // need the ratio between the two radius
// get the vector from the ellipse center to end of line
var dx = x - cx;
var dy = y - cy;
// get the vector that will normalise the ellipse rotation
var vx = Math.cos(-ang);
var vy = Math.sin(-ang);
// use that vector to rotate the line
var ddx = dx * vx - dy * vy;
var ddy = (dx * vy + dy * vx) * ratio; // lengthen or shorten dy
// get the angle to the line in normalise circle space.
var c = Math.atan2(ddy,ddx);
// get the vector along the ellipse x axis
var eAx = Math.cos(ang);
var eAy = Math.sin(ang);
// get the intercept of the line and the normalised ellipse
var nx = Math.cos(c) * r1;
var ny = Math.sin(c) * r2;
// rotate the intercept to the ellipse space
var ix = nx * eAx - ny * eAy
var iy = nx * eAy + ny * eAx
// cx,cy to ix ,iy is from the center to the ellipse circumference
The procedure can be optimised but for now that will solve the problem as presented.
Is point inside
Then to determine if the point is inside just compare the distances of the mouse and the intercept point.
var x = 200; // point to test
var y = 200;
// get the vector from the ellipse center to point to test
var dx = x - cx;
var dy = y - cy;
// get the vector that will normalise the ellipse rotation
var vx = Math.cos(ang);
var vy = Math.sin(ang);
// use that vector to rotate the line
var ddx = dx * vx + dy * vy;
var ddy = -dx * vy + dy * vx;
if( 1 >= (ddx * ddx) / (r1 * r1) + (ddy * ddy) / (r2 * r2)){
// point on circumference or inside ellipse
}
Example use of method.
function path(path){
ctx.beginPath();
var i = 0;
ctx.moveTo(path[i][0],path[i++][1]);
while(i < path.length){
ctx.lineTo(path[i][0],path[i++][1]);
}
if(close){
ctx.closePath();
}
ctx.stroke();
}
function strokeCircle(x,y,r){
ctx.beginPath();
ctx.moveTo(x + r,y);
ctx.arc(x,y,r,0,Math.PI * 2);
ctx.stroke();
}
function display() {
ctx.setTransform(1, 0, 0, 1, 0, 0); // reset transform
ctx.globalAlpha = 1; // reset alpha
ctx.clearRect(0, 0, w, h);
var cx = w/2;
var cy = h/2;
var r1 = Math.abs(Math.sin(globalTime/ 4000) * w / 4);
var r2 = Math.abs(Math.sin(globalTime/ 4300) * h / 4);
var ang = globalTime / 1500;
// find the intercept from ellipse center to mouse on the ellipse
var ratio = r1 / r2
var dx = mouse.x - cx;
var dy = mouse.y - cy;
var dist = Math.hypot(dx,dy);
var ex = Math.cos(-ang);
var ey = Math.sin(-ang);
var c = Math.atan2((dx * ey + dy * ex) * ratio, dx * ex - dy * ey);
var nx = Math.cos(c) * r1;
var ny = Math.sin(c) * r2;
var ix = nx * ex + ny * ey;
var iy = -nx * ey + ny * ex;
var dist = Math.hypot(dx,dy);
var dist2Inter = Math.hypot(ix,iy);
ctx.strokeStyle = "Blue";
ctx.lineWidth = 4;
ctx.beginPath();
ctx.ellipse(cx,cy,r1,r2,ang,0,Math.PI * 2,true)
ctx.stroke();
if(dist2Inter > dist){
ctx.fillStyle = "#7F7";
ctx.globalAlpha = 0.5;
ctx.fill();
ctx.globalAlpha = 1;
}
// Display the intercept
ctx.strokeStyle = "black";
ctx.lineWidth = 2;
path([[cx,cy],[mouse.x,mouse.y]])
ctx.strokeStyle = "red";
ctx.lineWidth = 5;
path([[cx,cy],[cx + ix,cy+iy]])
ctx.strokeStyle = "red";
ctx.lineWidth = 4;
strokeCircle(cx + ix, cy + iy, 6)
ctx.fillStyle = "white";
ctx.fill();
ctx.strokeStyle = "red";
ctx.lineWidth = 4;
strokeCircle(cx, cy, 6)
ctx.fillStyle = "white";
ctx.fill();
ctx.strokeStyle = "black";
ctx.lineWidth = 2;
strokeCircle(mouse.x, mouse.y, 4)
ctx.fillStyle = "white";
ctx.fill();
}
/** SimpleFullCanvasMouse.js begin **/
//==============================================================================
// Boilerplate code from here down and not related to the answer
//==============================================================================
var w, h, cw, ch, canvas, ctx, mouse, globalTime = 0, firstRun = true;
;(function(){
const RESIZE_DEBOUNCE_TIME = 100;
var createCanvas, resizeCanvas, setGlobals, resizeCount = 0;
createCanvas = function () {
var c,
cs;
cs = (c = document.createElement("canvas")).style;
cs.position = "absolute";
cs.top = cs.left = "0px";
cs.zIndex = 1000;
document.body.appendChild(c);
return c;
}
resizeCanvas = function () {
if (canvas === undefined) {
canvas = createCanvas();
}
canvas.width = innerWidth;
canvas.height = innerHeight;
ctx = canvas.getContext("2d");
if (typeof setGlobals === "function") {
setGlobals();
}
if (typeof onResize === "function") {
if(firstRun){
onResize();
firstRun = false;
}else{
resizeCount += 1;
setTimeout(debounceResize, RESIZE_DEBOUNCE_TIME);
}
}
}
function debounceResize() {
resizeCount -= 1;
if (resizeCount <= 0) {
onResize();
}
}
setGlobals = function () {
cw = (w = canvas.width) / 2;
ch = (h = canvas.height) / 2;
}
mouse = (function () {
function preventDefault(e) {
e.preventDefault();
}
var mouse = {
x : 0,
y : 0,
w : 0,
alt : false,
shift : false,
ctrl : false,
buttonRaw : 0,
over : false,
bm : [1, 2, 4, 6, 5, 3],
active : false,
bounds : null,
crashRecover : null,
mouseEvents : "mousemove,mousedown,mouseup,mouseout,mouseover,mousewheel,DOMMouseScroll".split(",")
};
var m = mouse;
function mouseMove(e) {
var t = e.type;
m.bounds = m.element.getBoundingClientRect();
m.x = e.pageX - m.bounds.left;
m.y = e.pageY - m.bounds.top;
m.alt = e.altKey;
m.shift = e.shiftKey;
m.ctrl = e.ctrlKey;
if (t === "mousedown") {
m.buttonRaw |= m.bm[e.which - 1];
} else if (t === "mouseup") {
m.buttonRaw &= m.bm[e.which + 2];
} else if (t === "mouseout") {
m.buttonRaw = 0;
m.over = false;
} else if (t === "mouseover") {
m.over = true;
} else if (t === "mousewheel") {
m.w = e.wheelDelta;
} else if (t === "DOMMouseScroll") {
m.w = -e.detail;
}
if (m.callbacks) {
m.callbacks.forEach(c => c(e));
}
if ((m.buttonRaw & 2) && m.crashRecover !== null) {
if (typeof m.crashRecover === "function") {
setTimeout(m.crashRecover, 0);
}
}
e.preventDefault();
}
m.addCallback = function (callback) {
if (typeof callback === "function") {
if (m.callbacks === undefined) {
m.callbacks = [callback];
} else {
m.callbacks.push(callback);
}
}
}
m.start = function (element) {
if (m.element !== undefined) {
m.removeMouse();
}
m.element = element === undefined ? document : element;
m.mouseEvents.forEach(n => {
m.element.addEventListener(n, mouseMove);
});
m.element.addEventListener("contextmenu", preventDefault, false);
m.active = true;
}
m.remove = function () {
if (m.element !== undefined) {
m.mouseEvents.forEach(n => {
m.element.removeEventListener(n, mouseMove);
});
m.element.removeEventListener("contextmenu", preventDefault);
m.element = m.callbacks = undefined;
m.active = false;
}
}
return mouse;
})();
// Clean up. Used where the IDE is on the same page.
var done = function () {
window.removeEventListener("resize", resizeCanvas)
mouse.remove();
document.body.removeChild(canvas);
canvas = ctx = mouse = undefined;
}
function update(timer) { // Main update loop
if(ctx === undefined){ return; }
globalTime = timer;
display(); // call demo code
requestAnimationFrame(update);
}
setTimeout(function(){
resizeCanvas();
mouse.start(canvas, true);
//mouse.crashRecover = done;
window.addEventListener("resize", resizeCanvas);
requestAnimationFrame(update);
},0);
})();
/** SimpleFullCanvasMouse.js end **/
If you have an ellipse of the form (x-x0)2/a2 + (y-y0)2/b2 = 1, then a point (x, y) is inside the ellipse if and only if (x-x0)2/a2 + (y-y0)2/b2 < 1. You can just test that inequality to see if the mouse is inside the ellipse.
To be able to draw a line to the edge of the ellipse: get the theta of the mouse with atan2 (don't use acos, you'll get incorrect results in quadrants III & IV), use the polar equation of the ellipse to solve for r, then convert back to rectangular coordinates and draw.

how can i make two objects belonging to the same array move independently of each other using javascript and the canvas tag?

I am trying to create a blackhole simulation, where all the balls that are outside of it go away from it at a given speed and those that fall on it are dragged towards the circle until they reach the center of it, where they would stop and disappear, here is my code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>blackhole simulation escape velocity</title>
<script>
var canvas, ctx;
var blackhole;
var circle;
var circles = new Array();
var G = 6.67e-11, //gravitational constant
pixel_G = G / 1e-11,
c = 3e8, //speed of light (m/s)
M = 12e31, // masseof the blackhole in kg (60 solar masses)
pixel_M = M / 1e32
Rs = (2 * G * M) / 9e16, //Schwarzchild radius
pixel_Rs = Rs / 1e3, // scaled radius
ccolor = 128;
function update() {
var pos, i, distance, somethingMoved = false;
for (i = 0; i < circles.length; i++) {
pos = circles[i].position;
distance = Math.sqrt(((pos.x - 700) * (pos.x - 700)) + ((pos.y - 400) * (pos.y - 400)));
if (distance > pixel_Rs-5 ) {
var delta = new Vector2D(0, 0);
var forceDirection = Math.atan2(pos.y - 400, pos.x - 700);
var evelocity = Math.sqrt((2 * pixel_G * pixel_M) / (distance * 1e-2));
delta.x += Math.cos(forceDirection) * evelocity;
delta.y += Math.sin(forceDirection) * evelocity;
pos.x += delta.x;
pos.y += delta.y;
somethingMoved = true;
} else {
var delta2 = new Vector2D (0,0);
var forceDirection2 = Math.atan2(pos.y - 400, pos.x - 700);
var g = (pixel_G*pixel_M)/(distance*distance*1e2);
delta2.x += Math.cos(forceDirection2)*g;
delta2.y += Math.sin(forceDirection2)*g;
pos.x -= delta2.x;
pos.y -= delta2.y;
somethingMoved = true;
circles[i].color -= 1;
if (pos.x == 700 && pos.y == 400){
somethingMoved = false;
};
}
}
if (somethingMoved) {
drawEverything();
requestAnimationFrame(update);
};
}
function drawEverything() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
blackhole.draw(ctx);
for (var i = 0; i < circles.length; i++) {
circles[i].draw(ctx);
}
}
function init(event) {
canvas = document.getElementById("space");
ctx = canvas.getContext('2d');
blackhole = new Ball(pixel_Rs, { x: 700,
y: 400 }, 0);
for (var i = 0; i < 200; i++) {
var vec2D = new Vector2D(Math.floor(Math.random() * 1400), Math.floor(Math.random() * 800));
circle = new Ball(5, vec2D, ccolor);
circles.push(circle);
}
drawEverything();
requestAnimationFrame(update);
}
function Ball(radius, position, color) {
this.radius = radius;
this.position = position;
this.color = color;
}
Ball.prototype.draw = function(ctx) {
var c=parseInt(this.color);
ctx.fillStyle = 'rgba(' + c + ',' + c + ',' + c + ',1)';
ctx.beginPath();
ctx.arc(this.position.x, this.position.y, this.radius, 0, 2 * Math.PI);
ctx.closePath();
ctx.fill();
};
function Vector2D(x, y) {
this.x = x;
this.y = y;
}
function onClick (){
canvas = document.getElementById ('space');
ctx = canvas.getContext ('2d')
canvas.addEventListener ("mousedown", init, false)
blackhole = new Ball (5, {x: 700,
y: 400 }, 0);
blackhole.draw (ctx) ;
}
window.onload = onClick;
</script>
<style>
body {
background-color:#021c36 ;
margin: 0px;
}
</style>
</head>
<body>
<canvas id = "space", width = "1400", height = "800">
</canvas>
</body>
</html>
Now as you can see, I created a second variable called delta2, but the problem is that it can't update the position of the circles, which in term makes it impossible to move the circle, can someone tell me what is wrong. Also, how can I make the big black circle after a certain amount of time, i know i probably should create a timer, but i don't know how they work
The gravity is too weak. I put a pseudo gravity to demonstrate.
var canvas, ctx;
var blackhole;
var circle;
var circles = new Array();
var bh = {
w:500,
h:300
};
bh.cx = Math.floor(bh.w/2);
bh.cy = Math.floor(bh.h/2)
var G = 6.67e-11, //gravitational constant
pixel_G = G / 1e-11,
c = 3e8, //speed of light (m/s)
M = 12e31, // masseof the blackhole in kg (60 solar masses)
pixel_M = M / 1e32
Rs = (2 * G * M) / 9e16, //Schwarzchild radius
pixel_Rs = Rs / 1e3, // scaled radius
ccolor = 128;
function update() {
var pos, i, distance, somethingMoved = false;
for (i = 0; i < circles.length; i++) {
pos = circles[i].position;
distance = Math.sqrt(((pos.x - bh.cx) * (pos.x - bh.cx)) + ((pos.y - bh.cy) * (pos.y - bh.cy)));
if (distance > pixel_Rs - 5) {
var delta = new Vector2D(0, 0);
var forceDirection = Math.atan2(pos.y - bh.cy, pos.x - bh.cx);
var evelocity = Math.sqrt((2 * pixel_G * pixel_M) / (distance * 1e-2));
delta.x += Math.cos(forceDirection) * evelocity;
delta.y += Math.sin(forceDirection) * evelocity;
pos.x += delta.x;
pos.y += delta.y;
somethingMoved = true;
} else {
var delta2 = new Vector2D(0, 0);
var forceDirection2 = Math.atan2(pos.y - bh.cy, pos.x - bh.cx);
// FIX THIS!!!
var g = 1;//(pixel_G * pixel_M) / (distance * distance * 1e2);
delta2.x += Math.cos(forceDirection2) * g;
delta2.y += Math.sin(forceDirection2) * g;
pos.x -= delta2.x;
pos.y -= delta2.y;
somethingMoved = true;
circles[i].color -= 1;
if (pos.x == bh.cx && pos.y == bh.cy) {
somethingMoved = false;
};
}
}
if (somethingMoved) {
drawEverything();
requestAnimationFrame(update);
};
}
function drawEverything() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
blackhole.draw(ctx);
for (var i = 0; i < circles.length; i++) {
circles[i].draw(ctx);
}
}
function init(event) {
canvas = document.getElementById("space");
canvas.width = bh.w;
canvas.height = bh.h;
ctx = canvas.getContext('2d');
blackhole = new Ball(5, { //pixel_Rs, {
x: bh.cx,
y: bh.cy
}, 0);
for (var i = 0; i < 200; i++) {
var vec2D = new Vector2D(Math.floor(Math.random() * bh.w), Math.floor(Math.random() * bh.h));
circle = new Ball(5, vec2D, ccolor);
circles.push(circle);
}
drawEverything();
requestAnimationFrame(update);
}
function Ball(radius, position, color) {
this.radius = radius;
this.position = position;
this.color = color;
}
Ball.prototype.draw = function(ctx) {
var c = parseInt(this.color);
ctx.fillStyle = 'rgba(' + c + ',' + c + ',' + c + ',1)';
ctx.beginPath();
ctx.arc(this.position.x, this.position.y, this.radius, 0, 2 * Math.PI);
ctx.closePath();
ctx.fill();
};
function Vector2D(x, y) {
this.x = x;
this.y = y;
}
function onClick() {
canvas = document.getElementById('space');
ctx = canvas.getContext('2d')
canvas.addEventListener("mousedown", init, false)
blackhole = new Ball(5, {
x: bh.cx,
y: bh.cy
}, 0);
blackhole.draw(ctx);
}
window.onload = onClick;
body {
background-color: #021c36;
margin: 0px;
}
<canvas id="space" , width="700" , height="400"></canvas>

Categories