How to animate a javascript triangle - javascript

I have this triangle code, but it seems to be not working. The code should act something like in this image, but instead, it only works in coding with Chrome platform.
What might be the reason behind that? Here is a fiddle.
function createTriangle(x1,y1,x2,y2,x3,y3,fillcolor,strokecolor,stroke) {
var triangle = new Object();
triangle.x1 =x1;
triangle.y1 = y1;
triangle.x2 = x2;
triangle.y2 = y2;
triangle.x3 = x3;
triangle.y3 = y3;
triangle.fillcolor = fillcolor;
triangle.draw = function() {
draw.triangle(this.x1, this.y1, this.x2, this.y2, this.x3, this.y3, this.fillcolor, this.strokecolor, this.stroke);
}
return triangle;
}
var triangle = createTriangle(350,100,360,100,360,360,'blue','black',6);
triangle.draw();
triangle.pointRight = true;
function moveTriangle() {
if (triangle.pointRight){
triangle.x1 += 2;
} else {
triangle.x1 -= 2;
}
if(triangle.x1 >= 300) {
triangle.pointRight = false;
} else if (triangle.x1 <= 250) {
triangle.pointRight = true;
}
triangle.draw();
setTimeout('moveTriangle();', 20)
}
moveTriangle();

I've created a simple animation trangle to the rectangle, it's not perfect, because I've no much time but maybe it'll helpful to you:
let initCoor = {
x1: ctx.canvas.width,
y1: 0,
x2:ctx.canvas.width,
y2:ctx.canvas.height/2,
x3:ctx.canvas.width,
y3:ctx.canvas.height/2,
x4:(ctx.canvas.width-ctx.canvas.width/5),
y4:0,
};
function initCanvas(){
ctx.clearRect(0, 0,ctx.canvas.width,ctx.canvas.height);
ctx.fillStyle = 'rgba(0,0,0,1)';
ctx.fillRect(0,0,ctx.canvas.width,ctx.canvas.height);
}
function draw_triangle(x1,y1,x2,y2,x3,y3,x4,y4, color) {
ctx.save();
ctx.beginPath();
ctx.moveTo(x1,y1);
ctx.lineTo(x1,y1);
ctx.lineTo(x2,y2);
ctx.lineTo(x3,y3);
ctx.lineTo(x4,y4)
ctx.fillStyle = color;
ctx.fill();
}
function setAnimate(){
initCoor.x4<=0?initCoor.x4=0:initCoor.x4-=10;
if(initCoor.y2>=ctx.canvas.height && initCoor.y3>=ctx.canvas.height){
initCoor.y2 = ctx.canvas.height;
initCoor.y3 = ctx.canvas.height;
if(initCoor.x3 <=0){
initCoor.x3=0
window.clearInterval(int);
}else{
initCoor.x3-=10
};
} else {
initCoor.y2+=10;
initCoor.y3+=10;
}
draw_triangle(initCoor.x1,initCoor.y1,initCoor.x2,initCoor.y2,initCoor.x3,initCoor.y3,initCoor.x4,initCoor.y4, '#CCC');
}
And working fiddle: https://jsfiddle.net/c7h5n34z/1/

Related

problem converting LSystems code from p5js to HTML Canvas javascript

I'm trying to convert this Daniel Shiffman tutorial from p5js to html5 canvas without a library:
var angle;
var axiom = "F";
var sentence = axiom;
var len = 100;
var rules = [];
rules[0] = {
a: "F",
b: "FF+[+F-F-F]-[-F+F+F]"
}
function generate() {
len *= 0.5;
var nextSentence = "";
for (var i = 0; i < sentence.length; i++) {
var current = sentence.charAt(i);
var found = false;
for (var j = 0; j < rules.length; j++) {
if (current == rules[j].a) {
found = true;
nextSentence += rules[j].b;
break;
}
}
if (!found) {
nextSentence += current;
}
}
sentence = nextSentence;
createP(sentence);
turtle();
}
function turtle() {
background(51);
resetMatrix();
translate(width / 2, height);
stroke(255, 100);
for (var i = 0; i < sentence.length; i++) {
var current = sentence.charAt(i);
if (current == "F") {
line(0, 0, 0, -len);
translate(0, -len);
} else if (current == "+") {
rotate(angle);
} else if (current == "-") {
rotate(-angle)
} else if (current == "[") {
push();
} else if (current == "]") {
pop();
}
}
}
function setup() {
createCanvas(400, 400);
angle = radians(25);
background(51);
createP(axiom);
turtle();
var button = createButton("generate");
button.mousePressed(generate);
}
This is my code and there is a problem with it that I am not able to debug... When I run the following code, I get the start of this tree with an error message prompting me to change rotate(-this.angle) to call the context. But when I fix the issue, the tree disappears & the rectangle in the "buildFlower()" function appears... why is this happening? :/ :
My code:
const init = () => {
const html = document.getElementsByTagName("html").item(0),
canvas = document.getElementsByTagName("canvas").item(0),
c = canvas.getContext("2d");
let flower;
const gui = new dat.GUI();
function line(x1, y1, x2, y2, color) {
c.strokeStyle = color;
c.beginPath();
c.moveTo(x1, y1);
c.lineTo(x2, y2);
c.stroke();
}
class Flower {
constructor(x, y, size) {
this.x = x;
this.y = y;
this.size = size;
this.angle = (Math.PI / 180) * 25;
this.axiom = "F";
this.sentence = this.axiom;
this.len = 100;
this.rules = [];
this.rules[0] = {
a: "F",
b: "FF+[+F-F-F]-[-F+F+F]",
};
}
generateLSystem() {
this.len *= 0.5;
let nextSentence = "";
for (let i = 0; i < this.sentence.length; i++) {
let current = this.sentence.charAt(i);
let found = false;
for (let j = 0; j < this.rules.length; j++) {
if (current == this.rules[j].a) {
found = true;
nextSentence += this.rules[j].b;
break;
}
}
if (!found) {
nextSentence += current;
}
}
this.sentence = nextSentence;
this.turtle();
}
turtle() {
c.resetTransform();
c.translate(100, getResolution().h);
for (let i = 0; i < this.sentence.length; i++) {
let current = [this.sentence.charAt(i)];
if (current == "F") {
line(0, 0, 0, -this.len);
c.translate(0, -this.len);
} else if (current == "+") {
c.rotate(this.angle);
} else if (current == "-") {
// WHEN I CHANGE THE LINE BELOW TO (`c.rotate`) THE ENTIRE THING DISAPPEARS.
rotate(-this.angle);
} else if (current == "[") {
current.push();
} else if (current == "]") {
current.pop();
}
}
}
buildFlower() {
c.beginPath();
c.rect(
getResolution().w / 2 - this.size / 2,
getResolution().h / 2 - this.size / 2,
this.size,
this.size
);
c.stroke();
}
}
const resize = () => {
canvas.width = w = window.innerWidth;
canvas.height = h = window.innerHeight;
console.log(`screen resolution: ${w}px × ${h}px`);
};
const getResolution = () => {
return { w: canvas.width, h: canvas.height };
};
const setup = () => {
c.clearRect(0, 0, getResolution().w, getResolution().h);
flower = new Flower(getResolution().w, getResolution().h, 200);
flower.generateLSystem();
gui.add(flower, "size", 0, 200);
gui.add(flower, "axiom");
};
setup();
const draw = (t) => {
c.fillStyle = "rgba(255, 255, 255, .5)";
c.fillRect(0, 0, w, h);
window.requestAnimationFrame(draw);
};
let w,
h,
last,
i = 0,
start = 0;
window.removeEventListener("load", init);
window.addEventListener("resize", resize);
resize();
window.requestAnimationFrame(draw);
};
window.addEventListener("load", init);
I've been trying for hrs and can't seem to debug :/
General suggestion: work in small sprints and run the code frequently to verify that it behaves as expected. The code here seems like it was built up in just a few long sprints without much validation for each component along the way. This apparently led to a buildup of complexity, causing confusion and subtle bugs.
Try to avoid premature abstractions like excessive functions and classes until the code is working correctly. At that point, the correct abstractions and cut points will be apparent.
Also, minimize the problem space by only introducing "bells and whistles"-type peripheral functionality once the core logic is working. When the basic drawing is failing, functionality like a GUI, resizing, a RAF loop and so forth just get in the way of progress. Add those after the basic drawing works.
The main reason for the disappearing drawing on the canvas is that resize() is called after setup(). When you resize the canvas, it wipes it clean. Call setup() after your initial resize() call:
window.removeEventListener("load", init);
window.addEventListener("resize", resize);
resize(); // <-- wipes the screen
setup(); // <-- draw after resize
window.requestAnimationFrame(draw);
You see a partial drawing showing up because your crash prevents the resize() from executing. This should be a big debug hint: some code after the drawing must be wiping it out.
The translation from p5's push() and pop() to HTML5 canvas doesn't appear correct:
} else if (current == "[") {
current.push();
} else if (current == "]") {
current.pop();
}
current is an array, but we don't want to mess with it. We're supposed to be pushing and popping the canvas context, not an array. These calls are context.save() and context.restore() in HTML5:
} else if (current === "[") {
c.save();
} else if (current === "]") {
c.restore();
}
A strange design choice is:
let current = [this.sentence.charAt(i)];
if (current == "F") {
Here, you've created an array of one element, then used coercion to compare it to a string. Always use === and don't create a one-element array unnecessarily:
// use const instead of let and [i] instead of charAt(i)
const current = this.sentence[i];
if (current === "F") {
I could analyze the design further and do a full rewrite/code review, but I'll leave it at this just to get you moving again and not belabor the point:
const init = () => {
const html = document.getElementsByTagName("html").item(0),
canvas = document.getElementsByTagName("canvas").item(0),
c = canvas.getContext("2d");
let flower;
// const gui = new dat.GUI();
function line(x1, y1, x2, y2, color) {
c.strokeStyle = color;
c.beginPath();
c.moveTo(x1, y1);
c.lineTo(x2, y2);
c.stroke();
}
class Flower {
constructor(x, y, size) {
this.x = x;
this.y = y;
this.size = size;
this.angle = (Math.PI / 180) * 25;
this.axiom = "F";
this.sentence = this.axiom;
this.len = 50;
this.rules = [];
this.rules[0] = {
a: "F",
b: "FF+[+F-F-F]-[-F+F+F]",
};
}
generateLSystem() {
this.len *= 0.5;
let nextSentence = "";
for (let i = 0; i < this.sentence.length; i++) {
let current = this.sentence[i];
let found = false;
for (let j = 0; j < this.rules.length; j++) {
if (current == this.rules[j].a) {
found = true;
nextSentence += this.rules[j].b;
break;
}
}
if (!found) {
nextSentence += current;
}
}
this.sentence = nextSentence;
this.turtle();
}
turtle() {
c.resetTransform();
c.translate(100, getResolution().h);
for (let i = 0; i < this.sentence.length; i++) {
const current = this.sentence[i];
if (current === "F") {
line(0, 0, 0, -this.len);
c.translate(0, -this.len);
} else if (current === "+") {
c.rotate(this.angle);
} else if (current === "-") {
c.rotate(-this.angle);
} else if (current === "[") {
c.save();
} else if (current === "]") {
c.restore();
}
}
}
buildFlower() {
c.beginPath();
c.rect(
getResolution().w / 2 - this.size / 2,
getResolution().h / 2 - this.size / 2,
this.size,
this.size
);
c.stroke();
}
}
const resize = () => {
canvas.width = w = window.innerWidth;
canvas.height = h = window.innerHeight;
console.log(`screen resolution: ${w}px × ${h}px`);
};
const getResolution = () => {
return { w: canvas.width, h: canvas.height };
};
const setup = () => {
c.clearRect(0, 0, getResolution().w, getResolution().h);
flower = new Flower(getResolution().w, getResolution().h, 200);
flower.generateLSystem();
//gui.add(flower, "size", 0, 200);
//gui.add(flower, "axiom");
};
const draw = (t) => {
c.fillStyle = "rgba(255, 255, 255, .5)";
c.fillRect(0, 0, w, h);
window.requestAnimationFrame(draw);
};
let w,
h,
last,
i = 0,
start = 0;
window.removeEventListener("load", init);
window.addEventListener("resize", resize);
resize();
setup();
window.requestAnimationFrame(draw);
};
window.addEventListener("load", init);
<canvas></canvas>

JavaScript Canvas create square [duplicate]

This question already has an answer here:
Drawing a rectangle on Canvas
(1 answer)
Closed 5 years ago.
I want to draw a square with a function like following.
How can I modify following function to create a square.
function square() {
var tool = this;
this.started = false;
this.mousedown = function (ev) {
context.beginPath();
context.moveTo(ev._x, ev._y);
tool.started = true;
};
this.mousemove = function (ev) {
if (tool.started && checkboxSquare.checked) {
context.lineTo(ev._x, ev._y);
context.stroke();
}
};
this.mouseup = function (ev) {
if (tool.started && checkboxSquare.checked) {
tool.mousemove(ev);
tool.started = false;
}
};
}
Here is a rework:
var Square;
(function(Square) {
var canvas = document.body.appendChild(document.createElement("canvas"));
canvas.style.border = "1px solid";
canvas.width = 800;
canvas.height = 800;
var context = canvas.getContext("2d");
var drawing = false;
var square = {
x: 0,
y: 0,
w: 0,
h: 0,
color: getColor()
};
var persistentSquares = [];
function getColor() {
return "rgb(" +
Math.round(Math.random() * 255) + ", " +
Math.round(Math.random() * 255) + ", " +
Math.round(Math.random() * 255) + ")";
}
function draw() {
context.clearRect(0, 0, canvas.width, canvas.height);
for (var pSquareIndex = 0; pSquareIndex < persistentSquares.length; pSquareIndex++) {
var pSquare = persistentSquares[pSquareIndex];
context.fillStyle = pSquare.color;
context.fillRect(pSquare.x, pSquare.y, pSquare.w - pSquare.x, pSquare.h - pSquare.y);
context.strokeRect(pSquare.x, pSquare.y, pSquare.w - pSquare.x, pSquare.h - pSquare.y);
}
context.strokeRect(square.x, square.y, square.w - square.x, square.h - square.y);
}
canvas.onmousedown = function(evt) {
square.x = evt.offsetX;
square.y = evt.offsetY;
square.w = evt.offsetX;
square.h = evt.offsetY;
drawing = true;
requestAnimationFrame(draw);
};
canvas.onmousemove = function(evt) {
if (drawing) {
square.w = evt.offsetX;
square.h = evt.offsetY;
requestAnimationFrame(draw);
}
};
function leave(evt) {
if (!drawing) {
return;
}
square.w = evt.offsetX;
square.h = evt.offsetY;
drawing = false;
persistentSquares.push(square);
square = {
x: 0,
y: 0,
w: 0,
h: 0,
color: getColor()
};
requestAnimationFrame(draw);
};
canvas.onmouseup = leave;
canvas.onmouseleave = leave;
})(Square || (Square = {}));
It's your lucky day! I was just working on something like this. If you use it for anything, be sure to credit me! ;)
Note that circle and oval are still a Work in Progress.
Link to JSFiddle that will be updated when I update the program: JSFiddle
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var mx=300;
var my=300;
var currentObject = {};
document.onmousemove = function(e){
mx=e.pageX-8;
my=e.pageY-8;
}
document.onmousedown = function(e){
var obj = document.getElementById("objSel").value;
currentObject.type=obj;
if(obj=="Rectangle"||currentObject.type=="Square"){
currentObject.x=e.pageX-8;
currentObject.y=e.pageY-8;
}
}
document.onmouseup = function(e){
mx=e.pageX-8;
my=e.pageY-8;
objects.push(complete(currentObject));
currentObject={};
}
var objects = [];
function render(){
ctx.clearRect(0,0,canvas.width,canvas.height);
ctx.beginPath();
ctx.moveTo(mx-5,my);
ctx.lineTo(mx+5,my);
ctx.moveTo(mx,my-5);
ctx.lineTo(mx,my+5);
ctx.strokeStyle="black";
ctx.lineWidth=2;
ctx.stroke();
ctx.closePath();
if(currentObject.type=="Rectangle"){
ctx.beginPath();
ctx.rect(currentObject.x,currentObject.y,mx-currentObject.x,my-currentObject.y);
ctx.stroke();
}
draw(complete(currentObject));
for(var i=0;i<objects.length;i++){
draw(objects[i]);
}
}
setInterval(render,5);
render();
function complete(o){
if(o.type=="Square"){
var sidelength = Math.max(Math.abs(mx-o.x),Math.abs(my-o.y));
var fix = function(input){
if(input==0){
return 1;
} else {
return input;
}
};
o.length=fix(Math.sign(mx-o.x))*sidelength;
o.height=fix(Math.sign(my-o.y))*sidelength;
} else if(o.type=="Rectangle"){
o.length=mx-o.x;
o.height=my-o.y;
}
return o;
}
function draw(o){
if(o.type=="Square"||o.type=="Rectangle"){
ctx.beginPath();
ctx.rect(o.x,o.y,o.length,o.height);
ctx.stroke();
}
}
<canvas id="canvas" style="border:1px solid black;" width="500" height="500">Please use a browser that supports the canvas element and make sure your Javascript is working properly.</canvas>
<br>
<span id="testing"></span>
<select id="objSel">
<option>Square</option>
<option>Rectangle</option>
<option>Circle</option>
<option>Oval</option>
</select>

How can i change the color of a javascript object?

I've created a simple code that looks a bit like "Impossible Game". I'm new with javascript so my question might sound a bit strange but i've created a few opjects like you can see below. When i change the color with ctx.fillstyle all my objects change this specific color. How can i give each object a different color?
Thanks ;)
var PlayerX;
var Blocka;
var Ground
var canvas = document.getElementById("gamefield");
ctx = canvas.getContext("2d");
var Gamespeed = 5;
var Gravity = 0.9;
var Score = 0;
var velocity = 0.01;
var jumping;
PlayerX = new Player();
Blocka = new Block(1);
Ground = new Gameground();
setInterval(Update, 20);
function startGame() {
}
function Player() {
// this staat voor verwijzing naar zichzelf
this.width = 30;
this.height = 50;
this.x = canvas.width / 4;
this.y = canvas.height / 3 * 2;
this.draw = function() {
ctx.fillRect(this.x, this.y, this.width, this.height);
}
}
function Block(kolb) {
this.width = 20;
this.height = 40;
this.show = true;
//this.x = canvas.width/2;
this.x = canvas.width + 20;
this.y = (canvas.height / 3 * 2) + 10;
this.draw = function() {
this.move();
if (this.show) {
if (kolb == 1) {
ctx.fillRect(this.x, this.y, this.width, this.height);
}
}
}
this.move = function() {
this.x -= Gamespeed;
this.death();
}
this.death = function() {
if (this.x <= 20) {
this.show = false;
}
}
}
function Gameground() {
// this staat voor verwijzing naar zichzelf
this.width = 800;
this.height = 150;
this.x = 0;
this.y = 450;
this.draw = function() {
ctx.fillStyle = "#00FFBF"
ctx.fillRect(this.x, this.y, this.width, this.height);
}
}
function Update() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
Blocka.draw();
PlayerX.draw();
if (PlayerX.x < Blocka.x + Blocka.width &&
PlayerX.x + PlayerX.width > Blocka.x &&
PlayerX.y < Blocka.y + Blocka.height &&
PlayerX.height + PlayerX.y > Blocka.y) {
// collision detected!
ctx.fillStyle = "#FF0000";
}
Ground.draw();
}
window.addEventListener("keydown", checkKeyPressed, false);
function checkKeyPressed(e) {
if (e.keyCode == "32") { //kijkt of de spatiebalk is ingedrukt
var interval1, interval2, velo, tijd;
velo = 0.00001;
tijd = 20;
interval1 = setInterval(plus, tijd);
function plus() {
if (velo < 20) {
velo += 1.5;
} else {
velo -= 1.5;
}
if (PlayerX.y > 480) {
clearInterval(interval1);
interval2 = setInterval(min, tijd);
}
PlayerX.y += velo;
console.log(PlayerX.y);
}
function min() {
if (velo < 20) {
velo += 1.5;
} else {
velo -= 1.5;
}
if (PlayerX.y < 430) {
clearInterval(interval2);
}
PlayerX.y -= velo;
console.log(PlayerX.y);
}
}
}
You can use ctx.save(); and ctx.restore(); before and after your individual color changes.
This will save the current context state before changing the color, and then restore it back to it's original state after that one specific rectangle was drawn, yet before the others are drawn.
See below for example.
ctx.save();
ctx.fillStyle = "#00FFBF";
ctx.fillRect(this.x, this.y, this.width, this.height);
ctx.restore();
--- EDIT ---
As per the comments on OP's question - another resolution is to ensure that you call the fillStyle function before each fillRect function. See example and fiddle (provided by OP) below.
this.draw = function(){
ctx.fillStyle = "#00FFBF";
ctx.fillRect(this.x, this.y, this.width, this.height);
}
Here's OP's fiddle - https://jsfiddle.net/Nielsvangils/v9hL9d3k/

Two animations to be performed in a single page one over the other in canvas

Actually i have a set of points which when connected forms like pipes connected horizontally and vertically. I want an animation to the pipes like this
var canvas1 = $("#mainCanvas1")[0];
var ctx1 = canvas1.getContext("2d");
var points = [[250,300],[250,150],[450,150],[450,50],[150,50],[150,300]];
var gradColor = ["#1FB0FF","#0AA9FF", "#009FF5",'#0092E0', "#0085CC"];
drawConnectionPipe(ctx1,points,15,gradColor[0],gradColor[1], gradColor[2],gradColor[3], gradColor[4]);
function drawConnectionPipe(ctx,coorinateArray,thickness,gradColorLight1, gradColorLight2,gradMidColor,gradColorDark1, gradColorDark2){
ctx.save();
gradColorNew = [gradColorDark2,gradColorLight1, gradColorLight2,gradMidColor,gradColorDark1];
var gradientObject = null;
for(var i=0; i<coorinateArray.length-1; i++){
var startPt = coorinateArray[i];
var endPt = coorinateArray[i+1];
gradientObject = ctx.createLinearGradient(startPt[0],startPt[1],endPt[0] , endPt[1]);
gradientObject.addColorStop(0, gradColorLight1);
gradientObject.addColorStop(0.25, gradColorLight2);
gradientObject.addColorStop(0.5, gradMidColor);
gradientObject.addColorStop(0.75, gradColorDark1);
gradientObject.addColorStop(1, gradColorDark2);
ctx.lineWidth=thickness;
ctx.strokeStyle = gradientObject;
ctx.lineJoin = "round";
ctx.beginPath();
ctx.moveTo(startPt[0],startPt[1]);
ctx.lineTo(endPt[0], endPt[1]);
ctx.closePath();
ctx.stroke();
//ctx.globalCompositeOperation = 'source-over';
}
// chnge the order
window.setTimeout(gameLoop, 150);
function gameLoop() {
if(gradColorNew.length == 5){
drawConnectionPipe(ctx,coorinateArray,thickness,gradColorNew[0],gradColorNew[1], gradColorNew[2],gradColorNew[3], gradColorNew[4]);
}
}
ctx.restore();
}
and inside that i want particles to move like this.
var ParticleGen = function () {
var particle = this;
// begin
// directions, upto
this.begin = function () {
var pipeBegin = points[pipeIndex];
var pipeEnds = points[pipeIndex + 1];
nx = pipeBegin.x;
ny = pipeBegin.y;
if (pipeBegin.x == pipeEnds.x) {
if (pipeBegin.y > pipeEnds.y) {
// endpoint y greater than start point y moving upwards
d = "up";
function animloop() {
if (ny > pipeEnds.y) {
ctx.clearRect(0, 0, w, h);
drawCircle(nx, ny);
ny--;
nx = nx;
requestAnimFrame(animloop);
}else if (ny == pipeEnds.y) {
cancelAnimationFrame(animloop);
particle.callBegin();
}
}
animloop();
} else if (pipeBegin.y < pipeEnds.y) {
d = "down";
function animloop1() {
if (ny < pipeEnds.y) {
ctx.clearRect(0, 0, w, h);
drawCircle(nx, ny);
ny++;
nx = nx;
requestAnimFrame(animloop1);
} else if (ny == pipeEnds.y) {
cancelAnimationFrame(animloop1);
particle.callBegin();
}
}
animloop1();
}
} else if (pipeBegin.y == pipeEnds.y) {
if (pipeBegin.x < pipeEnds.x) {
// start.x < end.x right movement
d = "right";
function animloop2() {
if (nx < pipeEnds.x) {
ctx.clearRect(0, 0, w, h);
drawCircle(nx, ny);
nx++;
ny = ny;
requestAnimFrame(animloop2);
} else if (ny == pipeEnds.y) {
cancelAnimationFrame(animloop2);
particle.callBegin();
}
}
animloop2();
} else if (pipeBegin.x > pipeEnds.x) {
d = "left";
function animloop3() {
if (nx > pipeEnds.x) {
ctx.clearRect(0, 0, w, h);
drawCircle(nx, ny);
nx--;
ny = ny;
requestAnimFrame(animloop3);
} else if (ny == pipeEnds.y) {
cancelAnimationFrame(animloop3);
particle.callBegin();
}
}
animloop3();
} else if (nx == pipeEnds.x) {
cancelAnimationFrame(animloop2);
particle.callBegin();
}
}
}
this.callBegin = function () {
if (pipeIndex <= 3) {
pipeIndex++;
console.log(pipeIndex)
particle.begin();
}
}
};
function drawCircle(cx, cy) {
// console.log(cx+ " :cx, cy: "+cy+ " : drawCircle")
ctx.beginPath();
ctx.arc(cx, cy, 2, 0, 2 * Math.PI, false);
ctx.fillStyle = "black";
ctx.fill();
ctx.closePath();
}
I have both the animations in different canvas and in differen page. I would like to combine them to get the effect of water flow.
I could do like this.
But the particle cannot be seen with no errors.
Please help.
Thank you in advance
you can do it by simply adding a line
ctx1.globalAlpha = 0.7;
in your function drawpipe() (at line 183).
this act as making your pipes transparent from 1 to 0.7
or you can draw your circle after pipes has been drawn.

Error in the if statement

This is now working properly, how can it be done without arrays (only with listeners), I need to change the code to be without arrays but with same functionality.
Here is the Javascript code. Its a simple drawing app.
$(document).ready(function(){
var x;
var y;
var canv = $("#myCanvas")[0];
var ctx = canv.getContext("2d");
var lines = new Array();
$("#myCanvas").click(function(event)
{
x = event.pageX - $("#myCanvas").offset().left;
y = event.pageY - $("#myCanvas").offset().top;
ctx.fillStyle = "#" + $("#barvaPolnila").val();
ctx.strokeStyle = "#" + $("#barvaCrte").val();
ctx.lineWidth = $("#sirina").val();
fill = $("input[name=polni]").is(":checked");
width = $("#dolzina").val();
shape = $("input[#name='lik']:checked").val();
if (shape == 'krog') {
ctx.beginPath();
ctx.arc(x, y, width, 0*Math.PI, 2*Math.PI);
if(fill)
ctx.fill();
else
ctx.stroke();
} else if(shape == "kvadrat") {
ctx.rect(x, y, width, width);
if(fill)
ctx.fill();
else
ctx.stroke();
} else {
if(lines[0] !== undefined) {
ctx.moveTo(lines[lines.length-1][0], lines[lines.length-1][1]);
ctx.lineTo(x, y);
ctx.stroke();
} else
ctx.beginPath();
lines.push([x, y]);
}
});
$("#skrij").click(function() {
gumb = $(this);
nadzornaPlosca = $("#nadzornaPlosca");
nadzornaPlosca.slideToggle(400, function() {
if($(this).is(":visible")) {
gumb.attr("value", "-");
} else {
gumb.attr("value", "+");
}
});
});
$("#zakljuci").click(function() {
if(lines[0] !== undefined) {
ctx.moveTo(lines[lines.length-1][0], lines[lines.length-1][1]);
ctx.lineTo(lines[0][0], lines[0][1]);
ctx.stroke();
if($("input[name=polni]").is(":checked")) {
ctx.beginPath();
for(i = 0; i < lines.length; i++) {
ctx.lineTo(lines[i][0], lines[i][1]);
}
ctx.closePath();
ctx.fill();
}
}
lines = new Array();
});
$("input[name=lik]").change(function() {
lines = new Array();
});
$("#brisi").click(function() {
ctx.clearRect(0, 0, canv.width, canv.height);
})
});
If you want to bind the function to the click event for those, you don't use an if() statement. Update the code to use the callback function for the click() function in jQuery as follows:
$("#pokazi").click(function(function() {
$("#nadzornaPlosca").slideToggle("slow");
});
$("#brisi").click(function() {
ctx.clearRect(0,0, 500, 500);
});
The last two bits are a bit broken, you're attaching event handlers but including an if and closing off the function before it's defined, do it like this:
$("#pokazi").click(function () {
$("#nadzornaPlosca").slideToggle("slow");
});
$("#brisi").click(function () {
ctx.clearRect(0,0, 500, 500);
});

Categories

Resources