Create a new object on button click - javascript

I am making an animation with Javascript. It is a ball that has a set speed and travels around inside a box. The animation works, and I have a button that increases the speed of the animations. I want to make a new button that creates a new ball when I click on it.
My Javascript code is the following:
var canvas = document.getElementById("canvas");
ctx = canvas.getContext("2d");
var fart = document.getElementById("fart")
var ny = document.getElementById("ny")
var circle = {
x:40,
y:50,
r:40,
}
var dx=5;
var dy=5;
var color = ["green", "blue", "yellow", "red", "orange", "pink"]
fart.onclick = function circleto (x,y,r) {
circle.x += 0;
ctx.clearRect(0, 0, canvas.width, canvas.height)
ctx.beginPath();
ctx.arc(circle.x, circle.y, circle.r, 0, 2*Math.PI);
ctx.closePath();
ctx.fillStyle = color[Math.floor(Math.random()*color.length)];
ctx.fill();
requestAnimationFrame(circleto);
if( circle.x<0+circle.r || circle.x>canvas.width-circle.r) dx=-dx;
if( circle.y<0 + circle.r || circle.y>canvas.height-circle.r) dy=-dy;
circle.x+=dx;
circle.y+=dy;
}
This is my HTML code:
<button id="fart">øk hastigheten</button>
<button id="ny">ny ball</button>
<canvas id="canvas" width="600px" height="400px"></canvas>

What you should do is storing circles inside an array.
And then loop through each item and change them seperatly.
I hope the following code can help as an example:
var
animationRunning = false,
circles = [{ x : 0, y : 0, r : 0 }]; // array
...
function step() {
if(animationRunning === true) {
ctx.clearRect(0, 0, canvas.width, canvas.height);
for(var i = O, length = circles.length; i < length; i++) {
var circle = circles[i];
ctx.beginPath();
ctx.arc(circle.x, circle.y, circle.r, 0, 2*Math.PI);
ctx.closePath();
ctx.fillStyle = color[Math.floor(Math.random()*color.length)];
ctx.fill();
if( circle.x<0+circle.r || circle.x>canvas.width-circle.r) dx=-dx;
if( circle.y<0 + circle.r || circle.y>canvas.height-circle.r) dy=-dy;
circle.x+=dx;
circle.y+=dy;
circles[i] = circle; // overide the previous version
}
requestAnimationFrame(circleto);
}
}
fart.onclick = function circleto (x,y,r) {
if(animationRunning === false) {
step();
}
}
ny.onclick = function circleto (x,y,r) {
circles.push({ x : 0, y : 0, r : 0 });
if(animationRunning === false) {
step();
}
}

<button id="fart">øk hastigheten</button>
<button id="ny">ny ball</button>
<canvas id="canvas" width="600px" height="400px"></canvas>
<script>
var canvas = document.getElementById("canvas");
ctx = canvas.getContext("2d");
var fart = document.getElementById("fart")
var ny = document.getElementById("ny")
var color = ["green", "blue", "yellow", "red", "orange", "pink"]
var circles = [
{
x:40,
y:50,
r:40,
dx:5,
dy:5,
},
];
fart.onclick = function circleto (x,y,r) {
ctx.clearRect(0, 0, canvas.width, canvas.height)
ctx.beginPath();
for (i in circles){
var circle = circles[i];
circle.x += 0;
ctx.arc(circle.x, circle.y, circle.r, 0, 2*Math.PI);
ctx.closePath();
ctx.fillStyle = color[Math.floor(Math.random()*color.length)];
ctx.fill();
if( circle.x<0+circle.r || circle.x>canvas.width-circle.r) circle.dx=-circle.dx;
if( circle.y<0 + circle.r || circle.y>canvas.height-circle.r) circle.dy=-circle.dy;
circle.x+=circle.dx;
circle.y+=circle.dy;
}
requestAnimationFrame(circleto);
}
ny.onclick = function newcircleto (x,y,r) {
var newcircle = {
x:40,
y:50,
r:40,
dx:5,
dy:5,
};
circles.push(newcircle);
}
</script>

Related

Couldn't make a wheel with four different color

I have been doing a lorry moving from left side to the right.
I made everything done but i'm asked to do a wheel with four different colors and I couldn't make it .
this is the code. -and every code that made as comment it was some tries for the wheel-.
it doesn't need to be inserted in this code, I'm fine with doing it all alone but if somebody done it for me I'll be grateful! :)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<title>My first animation in canvas</title>
<meta charset="utf-8">
<!-- http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"-->
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function () {
var canvas = $("#myCanvas");
var ctx = canvas.get(0).getContext("2d");
var playAnimation = true;
var startButton = $("#startAnimation");
var stopButton = $("#stopAnimation");
var increaseButton = $("#increase");
var decreaseButton = $("#decrease");
var changeDirection = $("#changeDirection");
var x = 0;
var b = 200;
var t = 200;
var w = 200;
var q = 255;
var cir = 240;
var cir2 = 90;
var ctx;
var direction = 1;
var speed = 10;
/*var cir1
var cir2
var cir3
var cir4
var cir5
var RAD = 100
var split = 4*/
startButton.hide();
startButton.click(function () {
$(this).hide();
stopButton.show();
animation = setInterval(function () {
animate();
}, speed);
});
stopButton.click(function () {
$(this).hide();
startButton.show();
clearInterval(animation)
});
increaseButton.click(function () {
changeSpeed(-10);
});
decreaseButton.click(function () {
changeSpeed(10);
});
changeDirection.click(function () {
direction *= -1;
})
function changeSpeed(changeValue) {
speed += changeValue;
clearInterval(animation)
animation = setInterval(function () {
animate();
}, speed);
}
/*function drawCircle(x,y,r,s,e,color) {
ctx.beginPath();
ctx.fillStyle = "#random";
ctx.arc(x,y,r,s,e)
ctx.closePath()
ctx.fill;
ctx.stroke;
drawCircle(150, 150, RAD,1.5*Math.PI,(Math.PI/2),"yellow");
drawCircle(150, 150, RAD,Math.PI/2,1.5*Math.PI,"brown");
drawCircle(150, 150, RAD,Math.PI,3*Math.PI,"blue");
drawCircle(150, 150, RAD,1.5*Math.PI,3*Math.PI,"orange");*/
function animate() {
x += direction;
b += direction;
t += direction;
w += direction;
q += direction;
cir += direction;
cir2 += direction;
/*cir1 += direction;
cir2 += direction;
cir3 += direction;
cir4 += direction;
cir5 += direction; */
//update
ctx.clearRect(0, 0, canvas.width(), canvas.height());
ctx.fillRect(x, 350, 190, 120);
ctx.fillRect(b, 410, 60, 60);
ctx.beginPath();
ctx.moveTo(t, 350);
ctx.lineTo(w, 400);
ctx.lineTo(q, 400);
ctx.closePath();
ctx.fillStyle = "#black";
ctx.fill();
/*ctx.beginPath();
ctx.fillStyle = "#random";
ctx.arc(x,y,r,s,e)
ctx.closePath()
ctx.fill;
ctx.stroke;
drawCircle(150, 150, RAD,1.5*Math.PI,(Math.PI/2),"yellow");
drawCircle(150, 150, RAD,Math.PI/2,1.5*Math.PI,"brown");
drawCircle(150, 150, RAD,Math.PI,3*Math.PI,"blue");
drawCircle(150, 150, RAD,1.5*Math.PI,3*Math.PI,"orange");*/
ctx.beginPath();
ctx.arc(cir, 490, 18, 0, 2 * Math.PI);
ctx.fillStyle = "red";
ctx.fill();
ctx.lineWidth = 4;
ctx.strokeStyle = '#black';
ctx.stroke();
ctx.beginPath();
ctx.arc(cir2, 490, 18, 0, 2 * Math.PI);
ctx.fillStyle = "red";
ctx.fill();
ctx.lineWidth = 4;
ctx.strokeStyle = '#black';
ctx.stroke();
};
var animation = setInterval(function () {
animate();
}, speed);
});
</script>
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Sofia&effect=neon|outline|emboss|shadow-multiple">
</head>
<style>
h1 {
background-color: black;
color: white;
}
.p1 {
font-family: "Sofia", sans-serif;
}
</style>
<body>
<canvas id="myCanvas" width="1900" height="720">
<!-- Insert fallback content here -->
</canvas>
<div>
<button id="startAnimation">Start</button>
<button id="stopAnimation">Stop</button>
<button id="increase"> Increase the speed</button>
<button id="decrease"> Decrease the speed</button>
<button id="changeDirection"> Change direction</button>
</div>
</body>
</html>
I created a fillCircle function that lets you draw a circle of n-slices with corresponding colors. I also introduced an angleOffset for drawing the wheels and added a y values to handle positioning on the vertical axis, to move the animation up a bit.
const angleOffsetFactor = 0.025;
let angleOffsetDelta = 0.05;
let angleOffset = 0;
increaseButton.click(function() {
changeSpeed(-10);
angleOffsetDelta += angleOffsetFactor;
});
decreaseButton.click(function() {
changeSpeed(10);
angleOffsetDelta -= angleOffsetFactor;
});
fillCircle(ctx, cir, y + 140, 18, [ 'red', 'yellow', 'blue', 'green' ], angleOffset);
const fillCircle = (ctx, x, y, radius, colors, angleOffset = 0) => {
const PI2 = Math.PI * 2;
const sectionAngle = PI2 / colors.length;
colors.forEach((color, index) => {
const angleStart = PI2 * (index / colors.length) + angleOffset;
const angleEnd = angleStart + sectionAngle;
ctx.beginPath();
ctx.fillStyle = color;
ctx.moveTo(x, y);
ctx.arc(x, y, radius, angleStart, angleEnd, false);
ctx.closePath();
ctx.fill();
});
};
Full example
const fillCircle = (ctx, x, y, radius, colors, angleOffset = 0) => {
const PI2 = Math.PI * 2;
const sectionAngle = PI2 / colors.length;
colors.forEach((color, index) => {
const angleStart = PI2 * (index / colors.length) + angleOffset;
const angleEnd = angleStart + sectionAngle;
ctx.beginPath();
ctx.fillStyle = color;
ctx.moveTo(x, y);
ctx.arc(x, y, radius, angleStart, angleEnd, false);
ctx.closePath();
ctx.fill();
});
};
$(document).ready(function() {
const ctx = $("#myCanvas").get(0).getContext("2d");
const playAnimation = true;
const startButton = $("#startAnimation");
const stopButton = $("#stopAnimation");
const increaseButton = $("#increase");
const decreaseButton = $("#decrease");
const changeDirection = $("#changeDirection");
let x = 0;
let y = 10;
let b = 200;
let t = 200;
let w = 200;
let q = 255;
let cir = 230;
let cir2 = 90;
let direction = 1;
let speed = 10;
const angleOffsetFactor = 0.025;
let angleOffsetDelta = 0.05;
let angleOffset = 0;
startButton.hide();
startButton.click(function() {
$(this).hide();
stopButton.show();
animation = setInterval(function() {
animate();
}, speed);
});
stopButton.click(function() {
$(this).hide();
startButton.show();
clearInterval(animation)
});
increaseButton.click(function() {
changeSpeed(-10);
angleOffsetDelta += angleOffsetFactor;
});
decreaseButton.click(function() {
changeSpeed(10);
angleOffsetDelta -= angleOffsetFactor;
});
changeDirection.click(function() {
direction *= -1;
})
function changeSpeed(changeValue) {
speed += changeValue;
clearInterval(animation)
animation = setInterval(function() {
animate();
}, speed);
}
function animate() {
x += direction;
b += direction;
t += direction;
w += direction;
q += direction;
cir += direction;
cir2 += direction;
angleOffset += angleOffsetDelta;
//update
ctx.fillStyle = "red";
ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
ctx.fillRect(x, y, 190, 120);
ctx.fillRect(b, y + 60, 60, 60);
ctx.beginPath();
ctx.moveTo(t, y);
ctx.lineTo(w, y + 50);
ctx.lineTo(q, y + 50);
ctx.closePath();
ctx.fillStyle = "black";
ctx.fill();
fillCircle(ctx, cir, y + 140, 18, [ 'red', 'yellow', 'blue', 'green' ], angleOffset);
ctx.beginPath();
ctx.arc(cir, y + 140, 18, 0, 2 * Math.PI);
//ctx.fillStyle = "red";
//ctx.fill();
ctx.lineWidth = 4;
ctx.strokeStyle = 'black';
ctx.stroke();
fillCircle(ctx, cir2, y + 140, 18, [ 'red', 'yellow', 'blue', 'green' ], angleOffset);
ctx.beginPath();
ctx.arc(cir2, y + 140, 18, 0, 2 * Math.PI);
//ctx.fillStyle = "red";
//ctx.fill();
ctx.lineWidth = 4;
ctx.strokeStyle = 'black';
ctx.stroke();
};
var animation = setInterval(function() {
animate();
}, speed);
});
h1 {
background-color: black;
color: white;
}
.p1 {
font-family: "Sofia", sans-serif;
}
#myCanvas {
border: thin solid grey;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Sofia&effect=neon|outline|emboss|shadow-multiple">
<canvas id="myCanvas" width="320" height="180"></canvas>
<div>
<button id="startAnimation">Start</button>
<button id="stopAnimation">Stop</button>
<button id="increase"> Increase the speed</button>
<button id="decrease"> Decrease the speed</button>
<button id="changeDirection"> Change direction</button>
</div>
Update
Here is a cleaner version with state, but it still needs a bit of work.
const ui = {
ctx: null,
buttons: {
start: null,
stop: null,
increase: null,
decrease: null,
changeDirection: null
},
colors: {
wheel: {
stroke: 'black',
fill: ['red', 'yellow', 'blue', 'green']
}
},
state: {
animationId: null,
play: false,
vars: {
x: 0,
y: 10,
b: 200,
t: 200,
w: 200,
q: 255,
cir: [40, 86, 230],
direction: 1,
speed: 10,
speedDelta: 10,
angleOffsetFactor: 0.025,
angleOffsetDelta: 0.05,
angleOffset: 0
}
}
}
const main = () => {
startAnimation();
};
const init = () => {
ui.ctx = $("#myCanvas").get(0).getContext("2d");
ui.state = {
...ui.state,
play: true
};
ui.buttons = {
...ui.buttons,
start: $("#startAnimation").hide().on('click', onStartClick),
stop: $("#stopAnimation").on('click', onStopClick),
increase: $("#increase").on('click', onIncreaseClick),
decrease: $("#decrease").on('click', onDecreaseClick),
changeDirection: $("#changeDirection").on('click', onChangeDirectionClick)
};
};
const startAnimation = () => {
ui.state.animationId = setInterval(animate, ui.state.vars.speed);
};
const stopAnimation = () => {
clearInterval(ui.state.animationId);
ui.state.animationId = null;
};
const restartAnimation = () => {
stopAnimation();
startAnimation();
};
const onStartClick = function() {
$(this).hide();
ui.buttons.stop.show();
restartAnimation();
};
const onStopClick = function() {
$(this).hide();
ui.buttons.start.show();
stopAnimation();
};
const onIncreaseClick = function() {
changeSpeed(-ui.state.vars.speedDelta);
ui.state.vars.angleOffsetDelta += ui.state.vars.angleOffsetFactor;
};
const onDecreaseClick = function() {
changeSpeed(ui.state.vars.speedDelta);
ui.state.vars.angleOffsetDelta -= ui.state.vars.angleOffsetFactor;
};
const onChangeDirectionClick = function() {
ui.state.vars.direction *= -1;
};
const changeSpeed = (changeValue) => {
ui.state.vars.speed += changeValue;
restartAnimation();
}
const animate = () => {
update();
drawTruck();
};
const update = () => {
const {
x, b, t, w, q, cir, angleOffset, angleOffsetDelta, direction
} = ui.state.vars;
ui.state.vars = {
...ui.state.vars,
x: x + direction,
b: b + direction,
t: t + direction,
w: w + direction,
q: q + direction,
cir: cir.map(v => v + direction),
angleOffset: angleOffset + angleOffsetDelta
};
};
const drawTruck = () => {
const { ctx } = ui;
const { colors } = ui;
const { state: { vars } } = ui;
ctx.fillStyle = "red";
ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
ctx.fillRect(vars.x, vars.y, 190, 100);
ctx.fillRect(vars.b, vars.y + 40, 60, 60);
ctx.beginPath();
ctx.moveTo(vars.t, vars.y);
ctx.lineTo(vars.w, vars.y + 30);
ctx.lineTo(vars.q, vars.y + 30);
ctx.closePath();
ctx.fillStyle = "black";
ctx.fill();
vars.cir.forEach(c => drawWheel(ctx, c, vars.y + 100, 18, colors.wheel, vars.angleOffset));
};
const drawWheel = (ctx, x, y, r, colors, angleOffset) => {
fillCircle(ctx, x, y, r, colors.fill, angleOffset);
ctx.beginPath();
ctx.arc(x, y, r, 0, 2 * Math.PI);
ctx.lineWidth = 4;
ctx.strokeStyle = colors.stroke;
ctx.stroke();
};
const fillCircle = (ctx, x, y, radius, colors, angleOffset = 0) => {
const PI2 = Math.PI * 2;
const sectionAngle = PI2 / colors.length;
colors.forEach((color, index) => {
const angleStart = PI2 * (index / colors.length) + angleOffset;
const angleEnd = angleStart + sectionAngle;
ctx.beginPath();
ctx.fillStyle = color;
ctx.moveTo(x, y);
ctx.arc(x, y, radius, angleStart, angleEnd, false);
ctx.closePath();
ctx.fill();
});
};
$(document).ready(function() {
init();
main();
});
#myCanvas {
border: thin solid grey;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Sofia&effect=neon|outline|emboss|shadow-multiple">
<canvas id="myCanvas" width="436" height="140"></canvas>
<div>
<button id="startAnimation">Start</button>
<button id="stopAnimation">Stop</button>
<button id="increase"> Increase the speed</button>
<button id="decrease"> Decrease the speed</button>
<button id="changeDirection"> Change direction</button>
</div>

how to add stroke and shadow only on mousemove in a canvas?

how can we give shadow and stroke for circle drawn using html canvas only during a mouse hover .
i have two cirles and want to have a shadow and stroke during mouse hover, but when i hover over the circles the code adds shadow and stroke, but once the mouse focuses out of the circles the shadow gets darker but doesnot go away.
<html>
<body>
<canvas id="myCanvas" width="1000" height="500" style="border:1px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.</canvas>
</body>
<script>
var canvas = document.getElementById("myCanvas"),
ctx = canvas.getContext("2d"),
circle = [
{x: 60, y: 50, r: 40, },
{x: 100, y: 150, r: 50,}// etc.
];
// render initial rects.
for (var i = 0; i < circle.length; i++) {
ctx.beginPath();
ctx.arc(circle[i].x, circle[i].y, circle[i].r,0,2*Math.PI);
ctx.fillStyle= "grey";
ctx.fill();
}
canvas.onmousemove = function (e){
// console.log("mouseover");
var cir = this.getBoundingClientRect(),
x= e.clientX - cir.left,
y = e.clientX - cir.top,
i = 0 , r;
console.log(r);
// ctx.clearRect(0, 0, c.width, c.height);
while (r = circle[i++])
{
ctx.beginPath();
ctx.arc(r.x,r.y,r.r,0,2*Math.PI)
if (ctx.isPointInPath(x, y))
{
ctx.shadowBlur= 10;
ctx.shadowColor = "grey";
ctx.lineWidth = 3;
ctx.strokeStyle = 'rgb(255,255,255)'
ctx.stroke();
}
else
{
ctx.arc(r.x,r.y,r.r,0,2*Math.PI)
}
}
};
</script>
</html>
canvas.onmousemove = function (e){
var cir = this.getBoundingClientRect(),
x= e.clientX - cir.left,
y = e.clientX - cir.top,
i = 0 , r;
/* add this */
ctx.clearRect(0, 0, canvas.width, canvas.height);
while (r = circle[i++])
{
ctx.beginPath();
ctx.arc(r.x,r.y,r.r,0,2*Math.PI)
if (ctx.isPointInPath(x, y))
{
ctx.shadowBlur= 10;
ctx.shadowColor = "grey";
ctx.lineWidth = 3;
ctx.strokeStyle = 'rgb(255,255,255)'
ctx.stroke();
}
else
{
ctx.arc(r.x,r.y,r.r,0,2*Math.PI)
}
}
/* add this */
for (var i = 0; i < circle.length; i++) {
ctx.beginPath();
ctx.arc(circle[i].x, circle[i].y, circle[i].r,0,2*Math.PI);
ctx.fillStyle= "grey";
ctx.fill();
}
};
I have modified your code to add stroke onmouse hover.
<html>
<body>
<canvas id="myCanvas" width="1000" height="500" style="border:1px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.</canvas>
</body>
<script>
var canvas = document.getElementById("myCanvas"),
ctx = canvas.getContext("2d"),
circle = [{
x: 60,
y: 50,
r: 40,
},
{
x: 100,
y: 150,
r: 50,
} // etc.
];
// render initial rects.
for (var i = 0; i < circle.length; i++) {
ctx.beginPath();
ctx.arc(circle[i].x, circle[i].y, circle[i].r, 0, 2 * Math.PI);
ctx.fillStyle = "blue";
ctx.fill();
}
canvas.onmousemove = function(e) {
var x = e.clientX,
y = e.clientY,
i = 0,
r;
ctx.clearRect(0, 0, canvas.width, canvas.height);
for (let i = 0; i < circle.length; i++) {
if ((x > circle[i].x - circle[i].r) && (y > circle[i].y - circle[i].r) && (x < circle[i].x + circle[i].r) && (y < circle[i].y + circle[i].r)) {
ctx.beginPath();
ctx.arc(circle[i].x, circle[i].y, circle[i].r, 0, 2 * Math.PI);
ctx.fillStyle = "blue";
ctx.fill();
ctx.shadowBlur = 10;
ctx.lineWidth = 3;
ctx.strokeStyle = 'rgb(255,255,255)';
ctx.shadowColor = 'grey';
ctx.stroke();
ctx.shadowColor = 'white';
ctx.shadowBlur = 0;
} else {
ctx.beginPath();
ctx.arc(circle[i].x, circle[i].y, circle[i].r, 0, 2 * Math.PI);
ctx.fillStyle = "blue";
ctx.fill();
ctx.shadowColor = 'white';
ctx.shadowBlur = 0;
}
}
};
</script>
</html>

Using eventListener to change stroke style after mobile movement

I'm trying to get the strokeStyle to change from black to red after the phone moves, but I can't seem to make it work! I want to be able to pull this up on my phone, and when I move the phone the curves on canvas will turn to blue.
Here is the code I have :
canvas = document.getElementById("c");
var ctx = c.getContext("2d");
for (var i = 0; i < 2000; i++) {
var j = 12.5 * i;
ctx.moveTo(-200 + j, 0);
ctx.bezierCurveTo(175 + j, 330, 1 + j, 600, j, 600);
ctx.bezierCurveTo(-150 + j, 750, 250 + j, 800, j + 75, 850);
//ctx.bezierCurveTo(200+j,850, 100+j, 1000, j, 1000);
}
window.addEventListener("devicemotion", handleDeviceMotion, true)
function handleDeviceMotion(e) {
var x = e.accelerationIncludingGravity.x;
var y = e.accelerationIncludingGravity.y;
var z = e.accelerationIncludingGravity.z;
document.getElementById("c").innerText = x;
document.getElementById("c").innerText = z;
document.getElementById("c").innerText = y;
setStrokeColor(ctx);
}
function setStrokeColor() {
document.getElementById("c").strokeStyle = "#FF0000";
}
//setBackgroundColor('x', color);
//setBackgroundColor('y', color);
//setBackgroundColor('z', color);
//function setBackgroundColor(var, color) {
// document.getElementbyId(var).color = "blue";
ctx.lineWidth = 5;
ctx.strokeStyle = '#000000';
ctx.stroke();
<canvas id="c" width="1200" height="1000" style="border: 1 px solid #c3c3c3" ;>
</canvas>
Unfortunately it's not possible to change the color of lines once they've been drawn. One option is to erase (or reset the state of the canvas to clean), then redraw the lines with the new color. Something along these lines:
var canvas = document.getElementById("c");
var ctx = c.getContext("2d");
var imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
function drawLines(color) {
for (var i = 0; i < 2000; i++) {
var j = 12.5 * i;
ctx.moveTo(-200 + j, 0);
ctx.bezierCurveTo(175 + j, 330, 1 + j, 600, j, 600);
ctx.bezierCurveTo(-150 + j, 750, 250 + j, 800, j + 75, 850);
}
ctx.lineWidth = 5;
ctx.strokeStyle = color;
ctx.stroke();
}
drawLines('#000000');
function handleDeviceMotion(e) {
// clear the lines
ctx.putImageData(imageData, 0, 0);
drawLines('#FF0000');
var x = e.accelerationIncludingGravity.x;
var y = e.accelerationIncludingGravity.y;
var z = e.accelerationIncludingGravity.z;
document.getElementById("c").innerText = x;
document.getElementById("c").innerText = z;
document.getElementById("c").innerText = y;
}
document.getElementById("simulateMotion").addEventListener('click', function() {
var e = {
accelerationIncludingGravity: {
x: 1,
y: 1,
z: 1
}
}
handleDeviceMotion(e);
});
<button id="simulateMotion">Simulate Motion</button>
<br/>
<br/>
<canvas id="c" width="1200" height="1000" style="border: 1 px solid #c3c3c3" ;>
</canvas>

HTML5 loop of a array of objects

I'm trying to make a grid that when clicking in a square it turns green, but i keep having trouble with adding objects to my array, if there preset they display fine but if add them once i click my mouse they wont render.
var canvas = document.getElementById("ctx");
var ctx = canvas.getContext("2d");
var Img = {};
Img.tileMap = new Image();
Img.tileMap.src = 'TitleMap.png';
WIDTH = 1536;
HEIGHT = 896;
currentImage = [32, 32];
ctx.strokeStyle = '#ffffff';
function createGrid() {
ctx.strokeStyle = '#ffffff'
for (var i = 0; i < WIDTH; i++) {
ctx.beginPath();
ctx.moveTo(i * 32, 0);
ctx.lineTo(i * 32, HEIGHT);
ctx.stroke();
}
for (var i = 0; i < HEIGHT; i++) {
ctx.beginPath();
ctx.moveTo(0, i * 32);
ctx.lineTo(1536, i * 32);
ctx.stroke();
}
}
var tiles = [{
x: 1,
y: 1
}];
var mousePos = null;
function getMousePos(canvas, evt) {
var rect = canvas.getBoundingClientRect();
return {
x: Math.round((evt.clientX - rect.left) / (rect.right - rect.left) *
canvas.width),
y: Math.round((evt.clientY - rect.top) / (rect.bottom - rect.top) *
canvas.height)
};
}
canvas.addEventListener('mousemove', function(evt) {
mousePos = getMousePos(canvas, evt);
}, false);
document.body.onmousedown = function() {
pos = {
x: Math.floor(mousePos.x / 32),
y: Math.floor(mousePos.y / 32),
};
tiles.push(pos);
}
function drawTiles() {
ctx.clearRect(0, 0, WIDTH, HEIGHT);
createGrid();
if (tiles.length) {
for (var id in tiles) {
ctx.fillStyle = "#42f456";
ctx.strokeStyle = '#42f456';
ctx.fillRect(tiles[id].x, tiles[id].y, 32, 32);
}
}
}
setInterval(drawTiles(), 1000 / 30);
<center>
<canvas id="ctx" width="1536" height="896" style="border:1px solid #ffffff;">
</canvas>
</center>
You were doing your setInterval wrong-- you want to pass the function, not call it-- otherwise whatever the function returns is what is passed to setInterval.
<body bgcolor="#000000">
<center><canvas id="ctx" width="1536" height="896" style="border:1px solid #ffffff;">
</canvas></center>
<script>
var canvas = document.getElementById("ctx");
var ctx = canvas.getContext("2d");
var Img = {};
Img.tileMap = new Image();
Img.tileMap.src = 'TitleMap.png';
WIDTH = 1536;
HEIGHT = 896;
currentImage = [32,32];
ctx.strokeStyle = '#ffffff';
function createGrid(){
ctx.strokeStyle = '#ffffff'
for (var i = 0 ; i < WIDTH; i++){
ctx.beginPath();
ctx.moveTo(i*32,0);
ctx.lineTo(i*32,HEIGHT);
ctx.stroke();
}
for (var i = 0 ; i < HEIGHT; i++){
ctx.beginPath();
ctx.moveTo(0,i*32);
ctx.lineTo(1536,i*32);
ctx.stroke();
}
}
var tiles = [{x:1,y:1}];
var mousePos = null;
function getMousePos(canvas, evt) {
var rect = canvas.getBoundingClientRect();
return {
x: Math.round((evt.clientX-rect.left)/(rect.right-rect.left)*canvas.width),
y: Math.round((evt.clientY-rect.top)/(rect.bottom-rect.top)*canvas.height)
};
}
canvas.addEventListener('mousemove', function(evt) {
mousePos = getMousePos(canvas, evt);
}, false);
document.body.onmousedown = function() {
pos = {
x:Math.floor(mousePos.x/32),
y:Math.floor(mousePos.y/32),
};
tiles.push(pos);
}
function drawTiles(){
ctx.clearRect(0,0,WIDTH,HEIGHT);
createGrid();
if(tiles.length){
for (var id in tiles){
ctx.fillStyle = "#42f456";
ctx.strokeStyle = '#42f456';
ctx.fillRect(tiles[id].x,tiles[id].y,32,32);
}
}
}
setInterval(drawTiles,1000/30);
</script>
</body>
Also, a few quick notes-- you're playing fast and loose with your var statements-- make sure if you don't want a variable to be global you declare it with a var. And also note that for...in loops are for iterating over object keys-- to iterate over an array, use a standard for loop. And finally, consider if a setInterval is even required-- seems like it might be sufficient to simply call drawTiles in the onmousedown after you push the new position into the tiles array.

add border to the outer area of slice in pie

http://jsfiddle.net/wm7pwL2w/8/
How can I add border to the outer area of slice in pie? Please check my jsfiddle. I have implemented Polar Area Chart here. I need each border to be of different color which I can specify. For example refer to this image
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext('2d');
console.log(ctx);
var center = {
x: 200,
y: 150
};
var myColor = ["#ccc", "#ccc", "#ccc", "#ccc", "#c01c3f"];
var myData = [20, 40, 50, 70, 100];
var myRadius = [150, 120, 80, 100, 70];
var myDistance = [5, 5, 2, 2, 2];
var myText = ['first', 'second', 'third', 'fourth', 'fifth'];
function getTotal(data) {
var myTotal = 0;
for (var j = 0; j < data.length; j++) {
myTotal += (typeof data[j] == 'number') ? data[j] : 0;
}
return myTotal;
}
function plotData() {
var lastend = 0;
var myTotal = getTotal(myData);
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
//ctx.strokeStyle = 'rgba(255,255,255,0.5)';
ctx.lineWidth = 1;
ctx.font="15px Arial";
for (var i = 0; i < myData.length; i++) {
ctx.save();
ctx.fillStyle = myColor[i];
ctx.beginPath();
ctx.translate(center.x, center.y);
var thisAngle = (Math.PI * 2 * (myData[i] / myTotal));
ctx.rotate(lastend + thisAngle / 2);
ctx.translate(myDistance[i], 0);
ctx.moveTo(0, 0);
ctx.arc(0, 0, myRadius[i], -(thisAngle / 2), thisAngle / 2, false);
ctx.closePath();
ctx.fill();
// ctx.stroke();
ctx.fillStyle = '#fff';
ctx.translate(0.6 * myRadius[i], 0);
ctx.rotate(-(lastend + thisAngle / 2));
ctx.fillText(myText[i], 0, 0);
ctx.restore();
lastend += thisAngle;
}
}
plotData();
Thanks for all the help.
You need to do it in two steps, first fill the shape then stroke just an arc. To do so you need to use a beginPath() for the outer border after filling it so to not stroke the complete shape.
...
ctx.closePath();
ctx.fill();
// original code stops
// insert this code
ctx.beginPath();
ctx.strokeStyle = '#079';
ctx.lineWidth = 9;
ctx.arc(0, 0, myRadius[i], -(thisAngle / 2), thisAngle / 2);
ctx.stroke();
// original code continues...
// ctx.stroke();
ctx.fillStyle = '#fff';
...
Updated fiddle
Use strokeStyle. JSFiddle
var lineColor = ["blue", "green", "purple", "pink", "aqua"];
for (var i = 0; i < myData.length; i++) {
............................
ctx.strokeStyle = lineColor[i];
ctx.fillStyle = myColor[i];
........
.............
ctx.fill();
ctx.stroke();
......................
}

Categories