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);
});
Related
Following is my code. I have face issue when I drag a point. The problem is that whenever I drag point all the line connect to one point. I need to have draggable points in a html5 Canvas. But I have a supplementary constraint: the 2 points must be linked by a line. When I drag a point, the line must be dynamically drawn, and still linked to the 2 points.
let points= [];
let drag_point= -1;
let pointSize= 6;
let canvas = document.querySelector("#myCanvas");
let w = canvas.width;
let h = canvas.height;
var ctx = canvas.getContext("2d");
$("#myCanvas").mousedown(function (e) {
var pos = getPosition(e);
drag_point = getPointAt(pos.x, pos.y);
console.log("pos", drag_point);
if (drag_point == -1) {
// no point at that position, add new point
drawlines(pos.x, pos.y);
points.push(pos);
}
});
$("#myCanvas").mousemove(function (e) {
if (drag_point != -1) {
// if currently dragging a point...
var pos = getPosition(e);
//...update that.points position...
points[drag_point].x = pos.x;
points[drag_point].y = pos.y;
redraw(); // ... and redraw myCanvas
}
});
$("#myCanvas").mouseup(function (e) {
drag_point = -1;
});
function getPosition(event) {
var rect = canvas.getBoundingClientRect();
var x = event.clientX - rect.left;
var y = event.clientY - rect.top;
console.log(x, y);
return { x: x, y: y };
}
function getPointAt(x, y) {
for (var i = 0; i < points.length; i++) {
if (
Math.abs(points[i].x - x) < pointSize &&
Math.abs(points[i].y - y) < pointSize
)
// check if x,y is inside points bounding box. replace with pythagoras theorem if you like.
return i;
}
return -1; // no point at x,y
}
function redraw() {
ctx.clearRect(0, 0, canvas.width, canvas.height); // clear canvas
for (var i = 0; i < points.length; i++) {
// draw all points again
drawlines(points[i].x, points[i].y);
}
}
function drawlines(x, y) {
drawImages(x, y);
if (points.length > 0) {
var last = points[points.length - 1];
ctx.beginPath();
ctx.moveTo(last.x, last.y);
ctx.lineTo(x, y);
ctx.strokeStyle = "blue";
ctx.stroke();
}
}
function drawImages(x, y) {
var ctx = document.getElementById("myCanvas").getContext("2d");
ctx.beginPath();
ctx.arc(x, y, pointSize, 0, Math.PI * 2, true);
ctx.strokeStyle = "red";
ctx.stroke();
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<canvas
id="myCanvas"
width="1000"
height="1000"
style="border: 1px solid #d3d3d3"
></canvas>
.
See code below...
I refactored your drawlines and drawImages to be called independently not inside a common loop, in my code we draw all lines, then we draw all circles, that way we don't have to change colors back and forth all the time and prevents any overlaps of the lines over the circles, also another change is in the mousedown I call the redraw instead of drawlines.
Looking at your code educated guess the problem is in your:
var last = points[points.length - 1];
that seems very off, technically that is making the last always be the same
let points = [{x:10,y:10},{x:55,y:50},{x:100,y:10}];
let drag_point = -1;
let pointSize = 6;
let canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
canvas.onmousedown = function(e) {
var pos = getPosition(e);
drag_point = getPointAt(pos.x, pos.y);
if (drag_point == -1) {
points.push(pos);
redraw();
}
};
canvas.onmousemove = function(e) {
if (drag_point != -1) {
var pos = getPosition(e);
points[drag_point].x = pos.x;
points[drag_point].y = pos.y;
redraw();
}
};
canvas.onmouseup = function(e) {
drag_point = -1;
};
function getPosition(event) {
var rect = canvas.getBoundingClientRect();
var x = event.clientX - rect.left;
var y = event.clientY - rect.top;
return {x, y};
}
function getPointAt(x, y) {
for (var i = 0; i < points.length; i++) {
if (
Math.abs(points[i].x - x) < pointSize &&
Math.abs(points[i].y - y) < pointSize
)
return i;
}
return -1;
}
function redraw() {
if (points.length > 0) {
ctx.clearRect(0, 0, canvas.width, canvas.height);
drawLines()
drawCircles()
}
}
function drawLines() {
ctx.beginPath();
ctx.moveTo(points[0].x, points[0].y);
ctx.strokeStyle = "blue";
ctx.lineWidth = 2;
points.forEach((p) => {
ctx.lineTo(p.x, p.y);
})
ctx.stroke();
}
function drawCircles() {
ctx.strokeStyle = "red";
ctx.lineWidth = 4;
points.forEach((p) => {
ctx.beginPath();
ctx.arc(p.x, p.y, pointSize, 0, Math.PI * 2, true);
ctx.stroke();
})
}
redraw()
<canvas id="myCanvas" width=160 height=160 style="border: 1px solid"></canvas>
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/
The script below draws an image on the left side of the screen and a selection box in the right. It then attempts to redefine the image drawn on the left on each new selection in the selection box on the right by making the imageID dependent on the selection. However, as you can see below, whatever number you select on the right the image remains the same (1) because whilst it might be redrawn, it is not redefined on selection. What I would like to happen is that on selection in the box on the right the number in the image changes with the selection box such that it always correlates with the selection. In other words, when you click on 2 the image changes to the 2nd image in images. I have found two ways of doing this but they are both flawed:
1: Define img in paint's render function. This works but it makes everything run very slowly and the hover animations on the image stop working as expected.
2: Define img in the makeSelectionInfo function. This also works but the hover animations completely stop working if this is done.
I apologise for the long code but I couldn't condense it any more. For the sake of brevity I have only included images for numbers between 1 & 5. Any help will be appreciated.
var c=document.getElementById('game'),
canvasX=c.offsetLeft,
canvasY=c.offsetTop,
ctx=c.getContext('2d');
images=['https://i.stack.imgur.com/KfN4z.jpg',
'https://i.stack.imgur.com/MyQS1.png',
'https://i.stack.imgur.com/3Vlfj.jpg',
'https://i.stack.imgur.com/u3NLH.jpg',
'https://i.stack.imgur.com/XnLwl.png'];
var curvedRect = function(text, x, y, w, h) {
this.text = text;
this.x = x;
this.y = y;
this.w = w;
this.h = h;
this.hovered = false;
this.clicked = false;
}
curvedRect.prototype.makeCurvedRect = function() {
var delta=0, theta=0, yRotation=this.y;
if (this.hovered) {
delta = 3;
shadowColor = '#000000';
shadowBlur = 20;
shadowOffsetX = 5;
shadowOffsetY = 5;
theta = -0.01;
} else {
delta = 0;
theta = 0;
shadowColor = '#9F3A9B';
shadowBlur = 0;
shadowOffsetX = 0;
shadowOffsetY = 0;
}
var x = this.x-delta;
var y = yRotation-delta;
var w = this.w+(2*delta);
var h = this.h+(2*delta);
var img=new Image();
img.src=images[this.text];
ctx.rotate(theta);
ctx.beginPath();
ctx.lineWidth='8';
ctx.strokeStyle='white';
ctx.moveTo(x+10, y);
ctx.lineTo(x+w-10, y);
ctx.quadraticCurveTo(x+w, y, x+w, y+10);
ctx.lineTo(x+w, y+h-10);
ctx.quadraticCurveTo(x+w, y+h, x+w-10, y+h);
ctx.lineTo(x+10, y+h);
ctx.quadraticCurveTo(x, y+h, x, y+h-10);
ctx.lineTo(x, y+10);
ctx.quadraticCurveTo(x, y, x+10, y);
ctx.shadowColor = shadowColor;
ctx.shadowBlur = shadowBlur;
ctx.shadowOffsetX = shadowOffsetX;
ctx.shadowOffsetY = shadowOffsetY;
ctx.stroke();
ctx.shadowBlur = 0;
ctx.shadowOffsetX = 0;
ctx.shadowOffsetY = 0;
ctx.drawImage(img, x+2.5, y+2.5, w-5, h-5);
ctx.rotate(-theta);
}
curvedRect.prototype.hitTest = function(x, y) {
return (x >= this.x) && (x <= (this.w+this.x)) && (y >= this.y) && (y <= (this.h+this.y));
}
var selectionForMenu = function(id, text, y) {
this.id = id;
this.text = text;
this.y = y;
this.hovered = false;
this.clicked = false;
this.lastClicked = false;
}
function makeTextForSelected(text, y) {
ctx.font='bold 12px Noto Sans';
ctx.fillStyle='white';
ctx.textAlign='center';
ctx.fillText(text, 200, y);
}
function makeSelectionInfo(text) {
makeTextForSelected(text, 375);
}
selectionForMenu.prototype.makeSelection = function() {
var fillColor='#A84FA5';
if (this.hovered) {
if (this.clicked) {
if (this.lastClicked) {
fillColor='#E4C7E2';
} else {
fillColor='#D5A9D3';
}
} else if (this.lastClicked) {
fillColor='#D3A4D0';
makeSelectionInfo(this.text);
} else {
fillColor='#BA74B7';
}
} else if (this.lastClicked) {
fillColor='#C78DC5';
makeSelectionInfo(this.text);
} else {
fillColor='#A84FA5';
}
ctx.beginPath();
ctx.fillStyle=fillColor;
ctx.fillRect(400, this.y, 350, 30)
ctx.stroke();
ctx.font='10px Noto Sans';
ctx.fillStyle='white';
ctx.textAlign='left';
ctx.fillText(this.text, 410, this.y+19);
}
selectionForMenu.prototype.hitTest = function(x, y) {
return (x >= 400) && (x <= (750)) && (y >= this.y) && (y <= (this.y+30)) && !((x >= 400) && (y > 450));
}
var Paint = function(element) {
this.element = element;
this.shapes = [];
}
Paint.prototype.addShape = function(shape) {
this.shapes.push(shape);
}
Paint.prototype.render = function() {
ctx.clearRect(0, 0, this.element.width, this.element.height);
for (var i=0; i<this.shapes.length; i++) {
try {
this.shapes[i].makeSelection();
}
catch(err) {}
try {
this.shapes[i].makeCurvedRect();
}
catch(err) {}
}
ctx.beginPath();
ctx.fillStyle='white';
ctx.fillRect(0, 0, 750, 25);
ctx.stroke();
for (var i=0; i<this.shapes.length; i++) {
try {
this.shapes[i].makeBox();
}
catch(err) {}
}
ctx.beginPath();
ctx.fillStyle='#BC77BA';
ctx.fillRect(0, 450, 750, 50);
ctx.stroke();
ctx.font='bold 10px Noto Sans';
ctx.fillStyle='#9F3A9B';
ctx.textAlign='center';
ctx.fillText('Phrase Practice', 365, 17);
for (var i=0; i<this.shapes.length; i++) {
try {
this.shapes[i].makeInteractiveButton();
}
catch(err) {}
}
}
Paint.prototype.setHovered = function(shape) {
for (var i=0; i<this.shapes.length; i++) {
this.shapes[i].hovered = this.shapes[i] == shape;
}
this.render();
}
Paint.prototype.setClicked = function(shape) {
for (var i=0; i<this.shapes.length; i++) {
this.shapes[i].clicked = this.shapes[i] == shape;
}
this.render();
}
Paint.prototype.setUnclicked = function(shape) {
for (var i=0; i<this.shapes.length; i++) {
if (shape.constructor.name==this.shapes[i].constructor.name) {
this.shapes[i].clicked = false;
if (shape instanceof selectionForMenu) {
this.shapes[i].lastClicked = this.shapes[i] == shape;
}
}
}
this.render();
}
Paint.prototype.select = function(x, y) {
for (var i=this.shapes.length-1; i >= 0; i--) {
if (this.shapes[i].hitTest(x, y)) {
return this.shapes[i];
}
}
return null
}
imageID = 0;
var paint = new Paint(c);
var img = new curvedRect(imageID, 112.5, 100, 175, 175);
var selection = [];
for (i=0; i<=30; i++) {
selection.push(new selectionForMenu(i, i, 25+(i*30)));
}
paint.addShape(img);
for (i=0; i<30; i++) {
paint.addShape(selection[i])
}
paint.render();
var clickedShape=0;
var i=0;
function mouseDown(event) {
var x = event.x - canvasX;
var y = event.y - canvasY;
var shape = paint.select(x, y);
if (shape instanceof selectionForMenu) {
imageTextID = shape.id;
if (i==0) {
clickedShape=shape;
i=1;
} else if (i==1) {
i=0;
}
}
paint.setClicked(shape);
}
function mouseUp(event) {
var x = event.x - canvasX;
var y = event.y - canvasY;
var shape = paint.select(x, y);
if (clickedShape instanceof selectionForMenu) {
if (x>400 && y>25 && y<450) {
paint.setUnclicked(shape);
} else if (shape && !(shape instanceof selectionForMenu)) {
paint.setUnclicked(shape);
}
}
}
function mouseMove(event) {
var x = event.x - canvasX;
var y = event.y - canvasY;
var shape = paint.select(x, y);
paint.setHovered(shape);
}
c.addEventListener('mousedown', mouseDown);
c.addEventListener('mouseup', mouseUp);
c.addEventListener('mousemove', mouseMove);
canvas {
z-index: -1;
margin: 1em auto;
border: 1px solid black;
display: block;
background: #9F3A9B;
}
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>uTalk Demo</title>
</head>
<body>
<canvas id="game" width = "750" height = "500"></canvas>
</body>
</html>
Fixed your code here https://jsfiddle.net/0wq0hked/2/
You can diff to see what I changed, but basically you weren't initializing and adding the multiple curvedRect to the Paint.shapes array. I also added the images as an attribute of curvedRect.
I also had to add a visible parameter to your shapes, as your mouse hover Paint.select function was not functioning properly. The way yours works, shapes that share the same (x,y) do not allow other shapes from being hovered even when they are not visible. Thus multiple shapes occupying the image area to the left stopped the hover from working properly. I suppose you could keep your Paint.select and instance/remove shapes when they are to be drawn, but you do not have shape removal functionality as far as I can tell.
Also, you call render on every event, this is a bad idea. Take a look at requestAnimationFrame and try drawing at the screen refresh rate rather than on user input.
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/
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.