I'm writing a simple game in which a user can move around a sprite. By clicking the stage, the sprite moves towards that location. The problem I'm facing is that I want to set a speed for this sprite. I do not know the values the user is going to click. I can't think of a way in which the sprite's speed is always the same.
The thing with PIXI.js is that you can set the x and y movement speed of the sprite. I want the result of those movement speeds to always be the same, for example 5. So if the sprite moves down, the y-speed would be 5. When the sprite is moving diagonally, the diagonal speed should be 5. I currently use this script, but the solution I came up with does not completely work, as the speed differs for each time I click.
Does anyone have any idea how to solve this problem?
var Container = PIXI.Container,
autoDetectRenderer = PIXI.autoDetectRenderer,
loader = PIXI.loader,
resources = PIXI.loader.resources,
Sprite = PIXI.Sprite;
var stage = new PIXI.Container(),
renderer = PIXI.autoDetectRenderer(1000, 1000);
document.body.appendChild(renderer.view);
PIXI.loader
.add("rocket.png")
.load(setup);
var rocket, state;
function setup() {
//Create the `tileset` sprite from the texture
var texture = PIXI.utils.TextureCache["animal.png"];
//Create a rectangle object that defines the position and
//size of the sub-image you want to extract from the texture
var rectangle = new PIXI.Rectangle(192, 128, 32, 32);
//Tell the texture to use that rectangular section
texture.frame = rectangle;
//Create the sprite from the texture
rocket = new Sprite(texture);
rocket.anchor.x = 0.5;
rocket.anchor.y = 0.5;
rocket.x = 50;
rocket.y = 50;
rocket.vx = 0;
rocket.vy = 0;
//Add the rocket to the stage
stage.addChild(rocket);
document.addEventListener("click", function(){
x = event.clientX - rocket.x;
y = event.clientY - rocket.y;
rocket.vmax = 5;
var total = Math.abs(x) + Math.abs(y);
var tx = x/total;
var ty = y/total;
rocket.vx = tx*rocket.vmax;
rocket.vy = ty*rocket.vmax;
});
state = play;
gameLoop();
}
function gameLoop() {
//Loop this function at 60 frames per second
requestAnimationFrame(gameLoop);
state();
//Render the stage to see the animation
renderer.render(stage);
}
function play(){
rocket.x += rocket.vx;
rocket.y += rocket.vy;
}
How about this? This would normalize x and y.
var total = Math.Sqrt(x * x + y * y);
and it looks x and y are missing 'var'.
var x = event.clientX - rocket.x;
var y = event.clientY - rocket.y;
Related
There are a few similar questions but none of the answers fix my issue. I am simulating a solar system using canvas. The animation function calls a function to update the positions and then these positions are shown on screen in the form of circles. I have tried not calling the function animate and simply drawing the bodies using the initial conditions and this works fine however when trying to draw them via the animate function nothing is drawn - no even the sun - even though the functions have been passed through.
Why are they not drawing on the canvas?
here is the code (i have removed the for loop which would draw all the planets to only draw the earth just for development purposes, i have also not copied in all the global variables at the top as they take up a lot of space):
var massList = [massMecury, massVenus, massEarth, massMars, massJupiter, massSaturn, massUranus, massNeptune];
var xPosList = [initialMecuryXPos, initialVenusXPos, initialEarthXPos, initialMarsXPos, initialJupiterXPos, initialSaturnXPos, initialUranusXPos, initialNeptuneXPos];
var yPosList = [initialMecuryYPos, initialVenusYPos, initialEarthYPos, initialMarsYPos, initialJupiterYPos, initialSaturnYPos, initialUranusYPos, initialNeptuneYPos];
var xVelList = [initialMecuryXVel, initialVenusXVel, initialEarthXVel, initialMarsXVel, initialJupiterXVel, initialSaturnXVel, initialUranusXVel, initialNeptuneXVel];
var yVelList = [initialMecuryYVel, initialVenusYVel, initialEarthYVel, initialMarsYVel, initialJupiterYVel, initialSaturnYVel, initialUranusYVel, initialNeptuneYVel];
//position and velocity scales so they fit on the screen
var posScale = 1.7E10;
//var velScale = 3E9;
var pauseButtonPressed = false;
function axis (){
var canvas = document.getElementById("solarsys");
c=canvas.getContext('2d');
//moves the origin to the centre of the page
c.translate(400, 275);
//makes the y axis grow up and shrink down
c.scale(1,-1);
//c.fillRect(-innerWidth/2,-innerHeight/2,innerWidth,innerHeight); if want a black background
}
function calAcc(i) {
//calculates distance between the earth and the sun
var r = Math.sqrt((xPosList[i]*xPosList[i]) + (yPosList[i]*yPosList[i]));
//calculates the angle of displacement between the earth and sun
var theta = Math.atan(yPosList[i]/xPosList[i]);
//calculate the force on the earth using F = Gm1m2/r^2
//force is towards the centre of the sun
var F = (G*massSun*massList[i])/(r*r);
//correct the angle based on which quadrant it is in
theta=Math.abs(theta);
if (xPosList[i] < 0 && yPosList[i] < 0){
theta = theta;
} else if (xPosList[i] > 0 && yPosList[i] < 0){
theta = Math.PI-theta;
} else if (xPosList[i] > 0 && yPosList[i] > 0){
theta = theta-Math.PI;
} else{
theta = (2*Math.PI)-theta;
}
var fX = Math.cos(theta)*F;
var fY = Math.sin(theta)*F;
//calculate earths acceleration using Newton 2nd a = F / m
var aX = (fX/massList[i]);
var aY = (fY/massList[i]);
return [aX, aY];
}
function leapfrog(i) {
var dt = 5000;
var a = calAcc(i);
xVelList[i] = xVelList[i] + (a[0]*dt);
yVelList[i] = yVelList[i] + (a[1]*dt);
xPosList[i] = xPosList[i] + (xVelList[i]*dt);
yPosList[i] = yPosList[i] + (yVelList[i]*dt);
}
function drawBody(i) {
c.beginPath();
c.arc(xPosList[i]/posScale, yPosList[i]/posScale, 1, 0, twoPi, false);
c.stroke();
c.closePath();
console.log('body drawn');
}
function drawSun(){
//draw a yellow circle - the sun
c.beginPath();
c.arc(0, 0, 2, 0, twoPi, false);
c.fillStyle = '#ffcc00';
c.fill();
c.stroke();
c.closePath();
}
function animate() {
var i = 2;
//for (var i=0; i< xPosList.length; i++){
leapfrog(i);
drawBody(i);
drawSun();
console.log(xPosList);
//clears canvas each new loop
c.clearRect(-innerWidth/2,-innerHeight/2,innerWidth,innerHeight);
}
window.onload=function() {
axis();
var looper=setInterval(animate,1);}
You have several problems to fix:
You have a setInterval which is executed with pauses of 1 milliseconds. This seems to be too quick and I absolutely do not see any guarantee that your browser will be able to draw the things to be drawn.
In your animate function you draw things, but instantly remove them. You need to clear the canvas first and only then draw things on the canvas.
Your code is very difficult to read, consider refactoring it
So I am rendering a Polyline with the Y-Values of a sin wave with the code below
var amplitude = 50;
var dx = (TWO_PI / period) * 10
var yValues = new Array(floor(widthOfWave / xSpacing));
var poly = [];
this.calculate = () => {
//Increment theta
theta += 0.02;
//For every x value, calculate the y value with SIN function
var x = theta;
for(var i = 0; i < yValues.length; i++) {
yValues[i] = sin(x) * amplitude;
x += dx;
}
this.render = () => {
this.calculate();
ellipseMode(CENTER);
beginShape();
for(var i = 0; i < yValues.length; i++) {
var temp = createVector((i * spacing), windowWidth + yValues[i]);
curveVertex(temp.x, temp.y);
poly.push(temp);
}
endShape();
}
Which renders the wave
This is exactly what I want, but the problem I am having is when I try to incorporate p5.collide2d (Github Link Here). I want to have an ellipse, the 'Player' in this case, be able to ride the wave by holding left and right on the keyboard arrows. I haven't gotten to the keyboard interaction, because I am currently stuck on having the Ellipse (a perfect circle) not just falling through the curve at sometimes.
Here is my code for the current collision I am testing with.
this.checkCollision = (objX, objY, objSize) => {
var hit = false;
var hit = collideCirclePoly(objX, objY, objSize, poly);
return hit;
}
//Check for the collision
var hit = hill.checkCollision(player1.x, player1.y, player1.size);
if(hit) player1.didCollide();
//Player's didCollide function
this.didCollide = () => {
newSpeed = this.ySpeed * -0.8;
this.ySpeed = newSpeed;
}
This is how the circle (the "Player") and the wave intereact whenever I try to run it though.
I can't seem to figure out why the interaction is happening this way. I have tried extending the bounds of the collision, but it just makes it appear very glitchy and it still sometimes just passes through the wave with what appears to be no collision.
I am fairly new to p5.js and processing, so I am most likely missing something very simple. Thanks for your help ahead of time!
I've been working on a specific animation in which I need to convert(with animation) a Rounded Rectangle Shape to Circle. I've checked the documentation of paper.js and haven't found any predefined function to achieve this.
-->
The animation needs to be smooth. As the number of rectangles I'm working with is very high, I can't use the "remove current rounded rect and redraw one more rounded version" method. It reduces the performace and the animation gets laggy.
This is the code I'm using to generate rounded rectangle.
// Had to paste something to post the question
// Though the whole code can be seen on codepen link
var rect = new Rectangle();
var radius = 100, origin = {x: 100, y: 100};
rect.size = new Size(radius, radius);
rect.center = new Point(origin.x, origin.y);
var cornerSize = radius / 4;
var shape = new Path.Rectangle(rect, cornerSize);
Prepared this Codepen example to show the progress.
If we can work out the whole animation using any other object types, that will be fine too. For now I can't find any any property which can transform the rounded rectangle to circle.
I'm also animating color of the object and position. I've gone through many documents to find out color animation.
PS: If there is any other(better) technique to animate colors of object, please share that too.
You will first have to create a path as a rounded rectangle. Then with each step in your animation you have to modify the eight segments of the path. This will only work with Path objects, not if your rectangle is a Shape.
The segment points and the handles have to be set like this:
κ (kappa) is defined in paper.js as Numerical.KAPPA (more on Kappa here).
The code to change the radius could look like this (Click here for the Sketch):
var rect = new Path.Rectangle(new Point(100, 100), new Size(100, 100), 30);
rect.fullySelected = true;
var step = 1;
var percentage = 0;
function onFrame(event) {
percentage += step;
setCornerRadius(rect, percentage)
if (percentage > 50 || percentage < 0) {
step *= -1;
}
}
function setCornerRadius(rectPath, roundingPercent) {
roundingPercent = Math.min(50, Math.max(0, roundingPercent));
var rectBounds = rectPath.bounds;
var radius = roundingPercent/100 * Math.min(rectBounds.width, rectBounds.height);
var handleLength = radius * Numerical.KAPPA;
l = rectBounds.getLeft(),
t = rectBounds.getTop(),
r = rectBounds.getRight(),
b = rectBounds.getBottom();
var segs = rectPath.segments;
segs[0].point.x = segs[3].point.x = l + radius;
segs[0].handleOut.x = segs[3].handleIn.x = -handleLength;
segs[4].point.x = segs[7].point.x = r - radius;
segs[4].handleOut.x = segs[7].handleIn.x = handleLength;
segs[1].point.y = segs[6].point.y = b - radius;
segs[1].handleIn.y = segs[6].handleOut.y = handleLength;
segs[2].point.y = segs[5].point.y = t + radius;
segs[2].handleOut.y = segs[5].handleIn.y = -handleLength;
}
Edit: I just found a much easier way using a shape. Not sure which approach performs faster.
Here is the implementation using a Shape (Click here for the Sketch).
var size = 100;
var rect = new Shape.Rectangle(new Rectangle(new Point(100, 100), new Size(size, size)), 30);
rect.strokeColor = "red";
var step = 1;
var percentage = 0;
function onFrame(event) {
percentage = Math.min(50, Math.max(0, percentage + step));
rect.radius = size * percentage / 100;
if (percentage >= 50 || percentage <= 0) {
step *= -1;
}
}
Change the corner size to the following
var cornerSize = circle.radius / 1;
The following is an example code I wrote just to show I handle certain things on my game:
https://jsfiddle.net/qk7ayx7n/25/
<canvas id = "canvas"></canvas>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
JS:
var canvas = document.getElementById("canvas");
var ctx=canvas.getContext("2d");
canvas.width = 750; //keeping ratio
canvas.height = 587; //keeping ratio
$('#canvas').css("height", window.innerHeight);
$('#canvas').css("width", window.innerHeight * 1.277); //keeping the ratio
//and also resizing according to the window(not to overflow)
var board = new Image();
board.src = "https://s21.postimg.org/ko999yaaf/circ.png";
var circle = new Image();
circle.src = "https://s21.postimg.org/4zigxdh7r/circ.png";
ctx.drawImage(board, 0, 0);
var x = 10, y = 10;
ctx.drawImage(circle, x, y);
startMoving();
function startMoving(){
if(y > 310) return;
y+=3;
ctx.clearRect(0,0,750,587);
ctx.drawImage(board, 0, 0);
ctx.drawImage(circle, x, y);
setTimeout(function(){startMoving()}, 30);
}
A little explanation: This is a simple board game. first the canvas is set to the board dimensions themselves in order to get the coordinates X Y correctly(this is not useful here but in my actual game yes).
then it is resized according to the window of the player, with regards to the actual ratio of the original board image. keeping the ratio is important for the quality of the image.
Now the movement is done with a simple timer in a function, once it gets to a certain X and Y the movement is stopped.
I have trouble getting the movement of the circle to move without breaks/lags in some browsers and devices (like on an cordova app), though it works fine usually. I know that the lags are caused by the way I handle things, but why?
also, I have trouble keeping the speed of the movement constant - +3 doesn't seem to move the same in every browser.
In most cases, you should use requestAnimationFrame for JavaScript-based animations to avoid choppiness. With this technique, the position is a function of time not how many execution frames take place. This way, fast computers will have more animation frames than slow computers, but you'll still perceive the same animation velocity. For example:
var x = 10, y = 10;
var startPos = 10;
var destPos = 310;
var startTime = Date.now();
var velocity = 0.1; // pixels per millisecond
var distance = destPos - startPos;
var duration = Math.abs(distance) / velocity;
requestAnimationFrame(startMoving);
function startMoving(now) {
var elapsedTime = Math.min(now - startTime, duration);
y = startPos + (elapsedTime * velocity);
ctx.clearRect(0,0,750,587);
ctx.drawImage(board, 0, 0);
ctx.drawImage(circle, x, y);
if (elapsedTime < duration)
requestAnimationFrame(startMoving);
}
I am trying to generate a Julia fractal in a canvas in javascript using math.js
Unfortunately every time the fractal is drawn on the canvas, it is rather slow and not very detailed.
Can anyone tell me if there is a specific reason this script is so slow or is it just to much to ask of a browser? (note: the mouse move part is disabled and it is still kinda slow)
I have tried raising and lowering the “bail_num” but everything above 1 makes the browser crash and everything below 0.2 makes everything black.
// Get the canvas and context
var canvas = document.getElementById("myCanvas");
var context = canvas.getContext("2d");
// Width and height of the image
var imagew = canvas.width;
var imageh = canvas.height;
// Image Data (RGBA)
var imagedata = context.createImageData(imagew, imageh);
// Pan and zoom parameters
var offsetx = -imagew/2;
var offsety = -imageh/2;
var panx = -2000;
var pany = -1000;
var zoom = 12000;
// c complexnumber
var c = math.complex(-0.310, 0.353);
// Palette array of 256 colors
var palette = [];
// The maximum number of iterations per pixel
var maxiterations = 200;
var bail_num = 1;
// Initialize the game
function init() {
//onmousemove listener
canvas.addEventListener('mousemove', onmousemove);
// Generate image
generateImage();
// Enter main loop
main(0);
}
// Main loop
function main(tframe) {
// Request animation frames
window.requestAnimationFrame(main);
// Draw the generate image
context.putImageData(imagedata, 0, 0);
}
// Generate the fractal image
function generateImage() {
// Iterate over the pixels
for (var y=0; y<imageh; y++) {
for (var x=0; x<imagew; x++) {
iterate(x, y, maxiterations);
}
}
}
// Calculate the color of a specific pixel
function iterate(x, y, maxiterations) {
// Convert the screen coordinate to a fractal coordinate
var x0 = (x + offsetx + panx) / zoom;
var y0 = (y + offsety + pany) / zoom;
var cn = math.complex(x0, y0);
// Iterate
var iterations = 0;
while (iterations < maxiterations && math.norm(math.complex(cn))< bail_num ) {
cn = math.add( math.sqrt(cn) , c);
iterations++;
}
// Get color based on the number of iterations
var color;
if (iterations == maxiterations) {
color = { r:0, g:0, b:0}; // Black
} else {
var index = Math.floor((iterations / (maxiterations)) * 255);
color = index;
}
// Apply the color
var pixelindex = (y * imagew + x) * 4;
imagedata.data[pixelindex] = color;
imagedata.data[pixelindex+1] = color;
imagedata.data[pixelindex+2] = color;
imagedata.data[pixelindex+3] = 255;
}
function onmousemove(e){
var pos = getMousePos(canvas, e);
//c = math.complex(-0.3+pos.x/imagew, 0.413-pos.y/imageh);
//console.log( 'Mouse position: ' + pos.x/imagew + ',' + pos.y/imageh );
// Generate a new image
generateImage();
}
function getMousePos(canvas, e) {
var rect = canvas.getBoundingClientRect();
return {
x: Math.round((e.clientX - rect.left)/(rect.right - rect.left)*canvas.width),
y: Math.round((e.clientY - rect.top)/(rect.bottom - rect.top)*canvas.height)
};
}
init();
The part of the code that is executed most is this piece:
while (iterations < maxiterations && math.norm(math.complex(cn))< bail_num ) {
cn = math.add( math.sqrt(cn) , c);
iterations++;
}
For the given canvas size and offsets you use, the above while body is executed 19,575,194 times. Therefore there are some obvious ways to improve performance:
somehow reduce the number of points for which the loop must be executed
somehow reduce the number of times these statements are executed per point
somehow improve these statements so they execute faster
The first idea is easy: reduce the canvas dimensions. But this is maybe not something you'd like to do.
The second idea can be achieved by reducing the value for bail_num, because then the while condition will be violated sooner (given that the norm of a complex number is always a positive real number). However, this will just result in more blackness, and gives the same visual effect as zooming out of the center of the fractal. Try for instance with 0.225: there just remains a "distant star". When bail_num is reduced too much, you wont even find the fractal anymore, as everything turns black. So to compensate you would then probably want to change your offset and zoom factors to get a closer view at the center of the fractal (which is still there, BTW!). But towards the center of the fractal, points need more iterations to get below bail_num, so in the end nothing is gained: you'll be back at square one with this method. It's not really a solution.
Another way to work along the second idea is to reduce maxiterations. However, this will reduce the resolution accordingly. It is clear that you will have fewer colors at your disposal, as this number directly corresponds to the number of iterations you can have at the most.
The third idea means that you would somehow optimise the calculations with complex numbers. It turns out to give a lot of gain:
Use efficient calculations
The norm that is calculated in the while condition could be used as an intermediate value for calculating the square root of the same number, which is needed in the next statement. This is the formula for getting the square root from a complex number, if you already have its norm:
__________________
root.re = √ ½(cn.re + norm)
root.im = ½cn.im/root.re
Where the re and im properties denote the real and imaginary components of the respective complex numbers. You can find the background for these formulas in this answer on math.stackexchange.
As in your code the square root is calculated separately, without taking benefit of the previous calculation of the norm, this will certainly bring a benefit.
Also, in the while condition you don't really need the norm (which involves a square root) for comparing with bail_num. You could omit the square root operation and compare with the square of bail_num, which comes down to the same thing. Obviously you would have to calculate the square of bail_num only once at the start of your code. This way you can delay that square root operation for when the condition is found true. The formula for calculating the square of the norm is as follows:
square_norm = cn.re² + cn.im²
The calls of methods on the math object have some overhead, since this library allows different types of arguments in several of its methods. So it would help performance if you would code the calculations directly without relying on math.js. The above improvements already started doing that anyway. In my attempts this also resulted in a considerable gain in performance.
Predefine colours
Although not related to the costly while loop, you can probably gain a litte bit more by calculating all possible colors (per number of iterations) at the start of the code, and store them in an array keyed by number of iterations. That way you can just perform a look-up during the actual calculations.
Some other similar things can be done to save on calculations: For instance, you could avoid translating the screen y coordinate to world coordinates while moving along the X axis, as it will always be the same value.
Here is the code that reduced the original time to complete by a factor of 10, on my PC:
Added intialisation:
// Pre-calculate the square of bail_num:
var bail_num_square = bail_num*bail_num;
// Pre-calculate the colors:
colors = [];
for (var iterations = 0; iterations <= maxiterations; iterations++) {
// Note that I have stored colours in the opposite direction to
// allow for a more efficient "countdown" loop later
colors[iterations] = 255 - Math.floor((iterations / maxiterations) * 255);
}
// Instead of using math for initialising c:
var cx = -0.310;
var cy = 0.353;
Replace functions generateImage and iterate by this one function
// Generate the fractal image
function generateImage() {
// Iterate over the pixels
var pixelindex = 0,
step = 1/zoom,
worldX, worldY,
sq, rootX, rootY, x0, y0;
for (var y=0; y<imageh; y++) {
worldY = (y + offsety + pany)/zoom;
worldX = (offsetx + panx)/zoom;
for (var x=0; x<imagew; x++) {
x0 = worldX;
y0 = worldY;
// For this point: iterate to determine color index
for (var iterations = maxiterations; iterations && (sq = (x0*x0+y0*y0)) < bail_num_square; iterations-- ) {
// root of complex number
rootX = Math.sqrt((x0 + Math.sqrt(sq))/2);
rootY = y0/(2*rootX);
x0 = rootX + cx;
y0 = rootY + cy;
}
// Apply the color
imagedata.data[pixelindex++] =
imagedata.data[pixelindex++] =
imagedata.data[pixelindex++] = colors[iterations];
imagedata.data[pixelindex++] = 255;
worldX += step;
}
}
}
With the above code you don't need to include math.js anymore.
Here is a smaller sized snippet with mouse events handled:
// Get the canvas and context
var canvas = document.getElementById("myCanvas");
var context = canvas.getContext("2d");
// Width and height of the image
var imagew = canvas.width;
var imageh = canvas.height;
// Image Data (RGBA)
var imagedata = context.createImageData(imagew, imageh);
// Pan and zoom parameters
var offsetx = -512
var offsety = -430;
var panx = -2000;
var pany = -1000;
var zoom = 12000;
// Palette array of 256 colors
var palette = [];
// The maximum number of iterations per pixel
var maxiterations = 200;
var bail_num = 0.8; //0.225; //1.15;//0.25;
// Pre-calculate the square of bail_num:
var bail_num_square = bail_num*bail_num;
// Pre-calculate the colors:
colors = [];
for (var iterations = 0; iterations <= maxiterations; iterations++) {
colors[iterations] = 255 - Math.floor((iterations / maxiterations) * 255);
}
// Instead of using math for initialising c:
var cx = -0.310;
var cy = 0.353;
// Initialize the game
function init() {
// onmousemove listener
canvas.addEventListener('mousemove', onmousemove);
// Generate image
generateImage();
// Enter main loop
main(0);
}
// Main loop
function main(tframe) {
// Request animation frames
window.requestAnimationFrame(main);
// Draw the generate image
context.putImageData(imagedata, 0, 0);
}
// Generate the fractal image
function generateImage() {
// Iterate over the pixels
console.log('generate', cx, cy);
var pixelindex = 0,
step = 1/zoom,
worldX, worldY,
sq_norm, rootX, rootY, x0, y0;
for (var y=0; y<imageh; y++) {
worldY = (y + offsety + pany)/zoom;
worldX = (offsetx + panx)/zoom;
for (var x=0; x<imagew; x++) {
x0 = worldX;
y0 = worldY;
// For this point: iterate to determine color index
for (var iterations = maxiterations; iterations && (sq_norm = (x0*x0+y0*y0)) < bail_num_square; iterations-- ) {
// root of complex number
rootX = Math.sqrt((x0 + Math.sqrt(sq_norm))/2);
rootY = y0/(2*rootX);
x0 = rootX + cx;
y0 = rootY + cy;
}
// Apply the color
imagedata.data[pixelindex++] =
imagedata.data[pixelindex++] =
imagedata.data[pixelindex++] = colors[iterations];
imagedata.data[pixelindex++] = 255;
worldX += step;
}
}
console.log(pixelindex);
}
function onmousemove(e){
var pos = getMousePos(canvas, e);
cx = -0.31+pos.x/imagew/150;
cy = 0.35-pos.y/imageh/30;
generateImage();
}
function getMousePos(canvas, e) {
var rect = canvas.getBoundingClientRect();
return {
x: Math.round((e.clientX - rect.left)/(rect.right - rect.left)*canvas.width),
y: Math.round((e.clientY - rect.top)/(rect.bottom - rect.top)*canvas.height)
};
}
init();
<canvas id="myCanvas" width="512" height="200"></canvas>