Making a circle that moves - javascript

Been trying to get something to work in HTML and I haven't been able to nail it down quite yet. Basically, I want to create a canvas and then make a circle inside the canvas that moves from edge of the canvas to edge of the canvas. Any suggestions?
EDIT:
Folks wanted what I have so far, so here it is:
<html>
<head>
<script type="text/javascript">
function draw () {
var canvas = document.getElementById('circle');
if (canvas.getContext) {
var context = canvas.getContext('2d');
context.fillStyle = "rgb(150,29,28)";
var startPoint = (Math.PI/180)*0;
var endPoint = (Math.PI/180)*360;
context.beginPath();
context.arc(200,200,150,startPoint,endPoint,true);
context.fill();
context.closePath();
}
}
}
</script>
</head>
<body onload="init();">
<canvas id="canvas" width="500" height="500"></canvas><br>
</body>
</html>
I'm not really sure how to get a circle onto the canvas (and I'm still shakey on the implementation thereof) as well as how to make it, y'know, move. I have examples of how to rotate something, but not really how to move it. Sorry for the inexperience guys, trying to learn HTML on my own, but the book I've got doesn't seem really descriptive on this aspect, even though it's a supposed to be teaching me HTML.

So up to now you have a code where you're able to draw a circle at a certain position onto the canvas surface, very well, now in order to make it look like it's moving you'll have to keep drawing it again and again with it's position slightly changed to give a smooth motion effect to it, it's a standard to draw things 60 times per second (I think that's because 60 frames per second is the most that the human eye can notice, or whatever). And of course, each time you draw it on another position, it's going to be necessary to clear the older drawing.
Let's change your code just a bit in order to make it animation-friendly:
<script type="text/javascript">
function init()
{
canvas = document.getElementById('canvas');
if(canvas.getContext)
context = canvas.getContext('2d');
else return;
setInterval(draw, 1000 / 60); // 60 times per second
}
function draw()
{
context.clearRect(0, 0, canvas.width, canvas.height);
context.fillStyle = "rgb(150,29,28)";
// var startPoint = (Math.PI/180)*0; Kinda redundant, it's just 0
// var endPoint = (Math.PI/180)*360; Again, it's just PI times 2
context.beginPath();
context.arc(200, 200, 150, 0, Math.PI * 2, true);
context.fill();
context.closePath();
}
</script>
</head>
<body onload="init();">
<canvas id="canvas" width="500" height="500"></canvas><br>
Now there are lots of funny ways to make an object move towards a fixed point, but the simplest is, of course, moving along a straight line. To do so you'll need
A vector containing the object's current position
A vector containing the object's target position
Let's change your code so we have those at hand
var canvas, context,
position = {x: 200, y: 200},
target = {x: 400, y: 400};
function init()
{
...
}
function draw()
{
context.clearRect(0, 0, canvas.width, canvas.height);
context.fillStyle = "rgb(150,29,28)";
context.beginPath();
context.arc(position.x, position.y, 150, 0, Math.PI * 2, true);
context.fill();
context.closePath();
}
Good! This way whenever you change one of the values in the position object, the position of your circle is going to be affected.
If you subtract the current position from the target position you'll get another vector which points straight to the target position coming from the current position right? So get that vector and just normalize it, turning it's length to 1, the result will actually be the (cosine, sine) of the angle from the target to the object's position. What that means is if you add that normalized vector to the object's current position, the object will move towards the target position 1 unit at a time.
Normlizing a vector is simply dividing it's components by it's length.
function normalize(v)
{
var length = Math.sqrt(v.x * v.x + v.y * v.y);
return {x: v.x / length, y: v.y / length};
}
var step = normalize({x: target.x - position.x, y: target.y - position.y});
Ok, now all we need to do is keep adding the step vector to the object's current position until it reaches the target position.
function normalize(v)
{
var length = Math.sqrt(v.x * v.x + v.y * v.y);
return {x: v.x / length, y: v.y / length};
}
var canvas, context,
position = {x: 200, y: 200},
target = {x: 400, y: 400},
step = normalize({x: target.x - position.x, y: target.y - position.y});
function init()
{
canvas = document.getElementById('canvas');
if(canvas.getContext)
context = canvas.getContext('2d');
else return;
setInterval(draw, 1000 / 60);
}
function draw()
{
context.clearRect(0, 0, canvas.width, canvas.height);
context.fillStyle = "rgb(150,29,28)";
context.beginPath();
context.arc(position.x, position.y, 150, 0, Math.PI * 2, true);
context.fill();
context.closePath();
position.x += step.x;
position.y += step.y;
}
And there you have it. Of course it's pretty basic code, you'll have to add a codition to check whether or not the object has arrived to the target otherwise it will just keep going past the target. If it's moving too slow, just scale the step vector by an arbitrary speed factor. Also in a real world app you'd have lot's of objects and not only just a circle so you'd have to make it entirely object-oriented since every object would have it's position, target position, color etc etc etc. A library to work with vectors would come in handy. This is one I wrote for myself some time ago: http://pastebin.com/Hdxg8dxn

Here you go, give this a crack -
<!DOCTYPE html>
<html>
<head>
<script>
function byId(e){return document.getElementById(e);}
function newEl(tag){return document.createElement(tag);}
function newTxt(txt){return document.createTextNode(txt);}
function toggleClass(element, newStr)
{
index=element.className.indexOf(newStr);
if ( index == -1)
element.className += ' '+newStr;
else
{
if (index != 0)
newStr = ' '+newStr;
element.className = element.className.replace(newStr, '');
}
}
function forEachNode(nodeList, func)
{
var i, n = nodeList.length;
for (i=0; i<n; i++)
{
func(nodeList[i], i, nodeList);
}
}
window.addEventListener('load', mInit, false);
var canvas, hdc;
var posx=50, posy=0, radius=50;
function circle(hdc, x, y, radius)
{
hdc.beginPath();
hdc.arc(x, y, radius, 0, 2*Math.PI);
hdc.stroke();
//arc(x,y,r,start,stop)
}
function mInit()
{
canvas = byId('tgtCanvas');
hdc = canvas.getContext('2d');
//circle(hdc, posx, posy, 50);
setInterval(animateStep, 50);
}
var velX = 2;
function animateStep()
{
posx += velX;
if (posx+radius > canvas.width)
velX *= -1;
else if (posx-radius < 0)
velX *= -1;
hdc.clearRect(0,0,canvas.width,canvas.height);
circle(hdc, posx, posy, radius);
}
</script>
<style>
</style>
</head>
<body>
<canvas id='tgtCanvas' width='256' height='256'></canvas>
</body>
</html>

Related

HTML5 Canvas Zoom on different points not working

I'm trying to implement zoom in an HTML5 Canvas. I came across other threads that explain how to do it, but they take advantage of the canvas' context, storing previous transformations. I want to avoid that.
So far I managed to do the following (https://jsfiddle.net/wfqzr538/)
<!DOCTYPE html>
<html>
<body style="margin: 0">
<canvas id="canvas" width="400" height="400" style="border: 1px solid #d3d3d3"></canvas>
<script>
const canvas = document.getElementById("canvas");
const context = canvas.getContext("2d");
let cursorX = 0,
cursorY = 0;
let zoom = 1;
canvas.onmousemove = mouseMove;
window.onkeydown = keyDown;
draw();
function mouseMove(evt) {
cursorX = evt.clientX;
cursorY = evt.clientY;
}
function keyDown(evt) {
if (evt.key == "p") {
zoom += 0.1;
}
if (evt.key == "m") {
zoom -= 0.1;
}
draw();
}
function draw() {
context.clearRect(0, 0, canvas.width, canvas.height);
const translationX = -cursorX * (zoom - 1);
const translationY = -cursorY * (zoom - 1);
context.translate(translationX, translationY);
context.scale(zoom, zoom);
context.fillRect(100, 100, 30, 30);
context.scale(1 / zoom, 1 / zoom);
context.translate(-translationX, -translationY);
}
</script>
</body>
</html>
The code above works If I zoom at the same location, but breaks as soon as I change it. For example, if I zoom in twice at the top left corner of the square, it works. However, if I zoom once at the top left corner, followed by zooming at the right bottom corner, it breaks.
I've been trying to fix this for a while now. I think it has something with not taking into account previous translations made in the canvas, but I'm not sure.
I'd really appreciate some help.
Not keeping previous state
If you don't want to keep the previous transform state then the is no way to do what you are trying to do.
There are many way to keep the previous state
Previous world state
You can transform all object's world state, in effect embedding the previous transform in the object's coordinates.
Eg with zoom and translate
object.x = object.x * zoom + translate.x;
object.y = object.y * zoom + translate.y;
object.w *= zoom;
object.h *= zoom;
then draw using default transform
ctx.setTransform(1,0,0,1,0,0);
ctx.fillRect(object.x, object.y, object.w, object.h);
Previous transformation state
To zoom at a point (absolute pixel coordinate) you need to know where the previous origin was so you can workout how far the zoom point is from that origin and move it correctly when zooming.
Your code does not keep track of the origin, in effect it assumes it is always at 0,0.
Example
The example tracks the previous transform state using an array that represents the transform. It is equivalent to what your code defines as translation and zoom.
// from your code
context.translate(translationX, translationY);
context.scale(zoom, zoom);
// is
transform = [zoom, 0, 0, zoom, translationX, translationY];
The example also changes the rate of zooming. In your code you add and subtract from the zoom, this will result in negative zooms, and when zooming in it will take forever to get to large scales. The scale is apply as a scalar eg zoom *= SCLAE_FACTOR
The function zoomAt zooms in or out at a given point on the canvas
const ctx = canvas.getContext("2d");
const transform = [1,0,0,1,0,0];
const SCALE_FACTOR = 1.1;
const pointer = {x: 0, y: 0};
var zoom = 1;
canvas.addEventListener("mousemove", mouseMove);
addEventListener("keydown", keyDown);
draw();
function mouseMove(evt) {
pointer.x = evt.clientX;
pointer.y = evt.clientY;
drawPointer();
}
function keyDown(evt) {
if (evt.key === "p") { zoomAt(SCALE_FACTOR, pointer) }
if (evt.key === "m") { zoomAt(1 / SCALE_FACTOR, pointer) }
}
function zoomAt(amount, point) {
zoom *= amount;
transform[0] = zoom; // scale x
transform[3] = zoom; // scale y
transform[4] = point.x - (point.x - transform[4]) * amount;
transform[5] = point.y - (point.y - transform[5]) * amount;
draw();
}
function draw() {
ctx.setTransform(1, 0, 0, 1, 0, 0);
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.setTransform(...transform);
ctx.fillRect(100, 100, 30, 30);
}
function drawPointer() {
draw();
ctx.lineWidth = 1;
ctx.strokeStyle = "black";
const invScale = 1 / transform[0]; // Assumes uniform scale
const x = (pointer.x - transform[4]) * invScale;
const y = (pointer.y - transform[5]) * invScale;
const size = 10 * invScale;
ctx.beginPath();
ctx.lineTo(x - size, y);
ctx.lineTo(x + size, y);
ctx.moveTo(x, y - size);
ctx.lineTo(x, y + size);
ctx.setTransform(1, 0, 0, 1, 0, 0); // to ensure line width is 1 px
ctx.stroke();
ctx.font = "16px arial";
ctx.fillText("Pointer X: " + x.toFixed(2) + " Y: " + y.toFixed(2), 10, 20);
}
* {margin: 0px}
canvas { border: 1px solid #aaa }
<canvas id="canvas" width="400" height="400"></canvas>
Update
I have added the function drawPointer which uses the transform to calculate the pointers world position, render a cross hair at the position and display the coordinates.

Animating an image to create rain effect

I’m trying to write a simple enough animation with javascript using HTML5 canvas. It’s an image of rain drops that I want to animate seamlessly. This is the image:
https://s31.postimg.org/475z12nyj/raindrops.png
This is how I'm currently animating it:
function Background() {
this.x = 0, this.y = 0, this.w = bg.width, this.h = bg.height;
this.render = function() {
ctx.drawImage(bg, 0, this.y++);
if (this.y <= -199) { //If image moves out of canvas, reset position to 0
this.y = 0;
}
}
}
I’m facing two issues though.
I can’t get the image to loop at all. It just falls down the one time, I need to have this on a loop so it’ll continue again when it starts to leave the canvas.
Once I know how to properly loop it, there is the issue that the rain isn’t suppose to fall down exactly vertically. It needs to fall down diagonally as the raindrops in the image suggest.
This is where it stops to be a simple enough animation.
Here’s my fiddle, it includes all my code. Thanks a lot.
PS: I’ll take any help with either Javascript or CSS I can get. But I do need the rain effect to be using the image only! I can’t accept anything else unfortunately.
I'd recommend splitting out your loop into an animation loop that calls update() and draw() separately. Update your state in update() and then render that state in draw().
Something like this (bit ragged, but you can perhaps make it better :) ):
var lastTick = 0;
var position = { x:0, y:0 };
var bg = document.getElementById('bg');
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
function update(gameTime) {
position.x += (70 * gameTime.diff / 1000);
position.y += (110 * gameTime.diff / 1000);
if (position.x > canvas.width) {
position.x = 0;
}
if (position.y > canvas.height) {
position.y = 0;
}
}
function draw(gameTime) {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.drawImage(bg, position.x, position.y, canvas.width, canvas.height);
ctx.drawImage(bg, position.x - canvas.width, position.y, canvas.width, canvas.height);
ctx.drawImage(bg, position.x, position.y - canvas.height, canvas.width, canvas.height);
ctx.drawImage(bg, position.x - canvas.width, position.y - canvas.height, canvas.width, canvas.height);
}
function loop(tick) {
var diff = tick - lastTick;
var gameTime = { tick:tick, diff:diff };
update(gameTime);
draw(gameTime);
requestAnimationFrame(loop);
lastTick = tick;
}
requestAnimationFrame(loop);
<title>Rain</title>
<meta charset="UTF-8">
<style>
canvas {
width:100vw;
height:100vh;
}
</style>
<img id="bg" src="https://s31.postimg.org/475z12nyj/raindrops.png" style="display:none;">
<canvas id="canvas"><h1>Canvas not supported</h1></canvas>

Growing infinite circles with JS and Canvas

I want to make a simple page that grows circles from its center ad infinitum. I'm almost there, but I can't figure out how to repeatedly grow them (resetting the radius i to 0 at a certain interval and calling the function again). I assume it will require a closure and some recursion, but I can't figure it out.
// Initialize canvas
var canvas = document.createElement("canvas");
var ctx = canvas.getContext("2d");
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
document.getElementsByTagName('body')[0].appendChild(canvas);
// Grow a circle
var i = 0;
var draw = function() {
ctx.fillStyle = '#000';
ctx.beginPath();
ctx.arc(canvas.width / 2, canvas.height / 2, i, 0, 2 * Math.PI);
ctx.fill();
i += 4;
window.requestAnimationFrame(draw);
}
draw();
Two things I'd do...
First, modify your draw function so that if the circle gets to a certain size, the i variable is reset back to zero. That starts the circle over again.
Second, add a setInterval timer to call your draw function at some time interval. See http://www.w3schools.com/js/js_timing.asp for details.
This setup will cause draw() to be called regularly, and the reset of i to zero makes it repeat.
So this did indeed require a closure. We wrap the initial function in a closure, and call it's wrapper function, which reinitializes I every time when called. draw() grows a single circle, and drawIt()() starts a new circle.
var drawIt = function(color) {
var i = 0;
return function draw() {
ctx.fillStyle = color;
ctx.beginPath();
ctx.arc(canvas.width/2, canvas.height/2, i, 0, 2 * Math.PI);
ctx.fill();
i+=1*growthFactor;
// Growing circles until they are huge
if (i < canvas.width) {
window.requestAnimationFrame(draw);
if (i === spacing) {
circles++
drawIt(nextColor())();
}
}
}
};
drawIt(nextColor())();
})();

Return squares to original state

I found this code on this site, but as I'm a novice with .js, I can't get my head around what the best practice would be to return a square to its original colour. ie, click on a square it changes color, click again it goes back to what it was.
Do I
just color the square on a second click? or
put an else if statement somewhere?
<script>
function getSquare(canvas, evt) {
var rect = canvas.getBoundingClientRect();
return {
x: 1 + (evt.clientX - rect.left) - (evt.clientX - rect.left)%10,
y: 1 + (evt.clientY - rect.top) - (evt.clientY - rect.top)%10
};
}
function drawGrid(context) {
for (var x = 0.5; x < 10001; x += 10) {
context.moveTo(x, 0);
context.lineTo(x, 10000);
}
for (var y = 0.5; y < 10001; y += 10) {
context.moveTo(0, y);
context.lineTo(10000, y);
}
context.strokeStyle = "#ddd";
context.stroke();
}
function fillSquare(context, x, y){
context.fillStyle = "red";
context.fillRect(x,y,9,9);
}
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
drawGrid(context);
canvas.addEventListener('click', function(evt) {
var mousePos = getSquare(canvas, evt);
fillSquare(context, mousePos.x, mousePos.y);
}, false);
</script>
First of all it's a bit dangerous to draw over a previous state, because sometimes you get 'ghosting'. but ignores this for now
And to get back to your questions, as nearly always it depends on the situation.
If you have a canvas that only changes when a user interacts you can (should) use an event handler to trigger a draw.
When you have other things animated you should split animation and values. (requestAnimationFrame) This does however require more work since everything should be stored as a variable.
You are going to need an if statement in the draw-code becaus you need to determine when it's colored and when not.
//https://jsfiddle.net/dgq9agy9/2/
function fillSquare(context, x, y){
var imgd = context.getImageData(x, y, 1, 1);
var pix = imgd.data;
console.log("rgba="+pix[0]+"-"+pix[1]+"-"+pix[2]+"-"+pix[3]);
if(pix[0]==0){
context.fillStyle = "red";
}else if(pix[0]==255){
context.fillStyle = "black";}
context.fillRect(x,y,9,9);
}
In my example I check if the pixel you clicked is red or black and switch them.
This is an easy solution because you don't need any extra variables, but it's not very clean.
If you want a clean solution, you could create an 2d-array with 1 or 0 values and draw a color depending on the number. But this requires alot/more work. Like translation the X,Y mouse click to the N-th number of square.(something like this: color_arr[x/9][y/9])

How do you copy an animation in canvas

I have this animation of a semicircle being drawn, and I basically want to copy it, and move the copy down 60px then add a delay of a second to the new one, So that it draws a "B"
html
<canvas id="thecanvas"></canvas>
script
var can = document.getElementById('thecanvas');
ctx = can.getContext('2d');
can.width = window.innerWidth;
can.height = window.innerHeight;
window.drawCircle = function (x, y) {
segments = 90, /* how many segments will be drawn in the space */
currentSegment = 0,
toRadians = function (deg) {
return (Math.PI / 180) * deg;
},
getTick = function (num) {
var tick = toRadians(180) / segments; /*360=full, 180=semi, 90=quarter... */
return tick * num;
},
segment = function (end) {
end = end || getTick(currentSegment);
ctx.clearRect(0, 0, can.width, can.height);
ctx.beginPath();
ctx.arc(x, y, 60, (1.5 * Math.PI), end + (1.5 * Math.PI), false);
ctx.stroke();
ctx.closePath();
};
ctx.lineWidth = 5;
ctx.strokeStyle = 'rgba(0,0,0,0.5)';
setTimeout(function render() {
segment(getTick(currentSegment));
currentSegment += 1;
if (currentSegment < segments) {
setTimeout(render, 5);
} else {
currentTick = 0;
}
}, 250);
};
drawCircle(100, 100);
Here is a fiddle http://jsfiddle.net/zhirkovski/bJqdN/
first you can put the setTimeout function outside of your drawCircle method.
Then you have at least 2 options :
to create an "endDraw" Event which will be dispatched at the end of 1 draw. When this event is handle, just call again the drawCircle method. To achieve this, of course you need a main method to call the first drawCircle.
To make a better solution, you can describe a workflow of calls. ie describe a list of method to call and for each of them the start frame:
var workflow = [{method:"drawCircle", frame:0, x:100, y:100}, //the first half circle at the frame 0, x=100, y=100
{method:"drawCircle", frame:1000, x:100, y:190}]; //the second half circle starting at frame 1000, x=100, y=190
The your main timer will just be configured to use this array to know what call to do

Categories