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.
Related
I have been studying JS for a few days, but I need to draw a parallelogram and allow user to change its angles by dragging one of its points. I took a code from a related question, and tried to change it (I know, it's a nightmare). But the 4th point doesn't work properly. I get this:
https://i.stack.imgur.com/PAjE6.png
How can I make the 4th point create a parallelogram?
var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");
var cw = canvas.width;
var ch = canvas.height;
var mouse = {};
var draggable = false;
context.lineWidth = 2;
context.strokeStyle = "blue";
var coordinates = [];
var isDone = false;
var clicks = 0;
canvas.addEventListener("mousedown", function(e) {
handleMouseDown(e);
});
function GetMassCenterAndFourthPoint(knownpoints) {
let point4X = knownpoints[2].x - knownpoints[1].x + knownpoints[0].x;
let point4Y = knownpoints[2].y - knownpoints[1].y + knownpoints[0].y;
coordinates.push({
x: point4X,
y: point4Y
});
}
function handleMouseDown(e) {
mouse = oMousePos(canvas, e);
//if isDone you can drag
if (isDone) {
for (index = 0; index < coordinates.length; index++) {
// you draw a small circle no stroke, no fill
context.beginPath();
context.arc(
coordinates[index].x,
coordinates[index].y,
5,
0,
2 * Math.PI
);
// if the mouse is inside the circle
if (context.isPointInPath(mouse.x, mouse.y)) {
// you can drag this point
// I'm using index + 1 because index == 0 is false
draggable = index + 1;
// if I have a point a can break the loop
break;
}
}
} else {
coordinates.push({
x: mouse.x,
y: mouse.y
});
drawPolygon();
clicks++;
if (clicks === 3) {
isDone = true;
}
}
}
function drawPolygon() {
context.clearRect(0, 0, cw, ch);
if (isDone) {
GetMassCenterAndFourthPoint(coordinates);
}
context.beginPath();
context.moveTo(coordinates[0].x, coordinates[0].y);
for (index = 1; index < coordinates.length; index++) {
context.lineTo(coordinates[index].x, coordinates[index].y);
}
context.closePath();
context.stroke();
// Additionaly I'm drawing a small circle around every point
// you can delete this.
for (index = 0; index < coordinates.length; index++) {
context.beginPath();
context.arc(coordinates[index].x, coordinates[index].y, 5, 0, 2 * Math.PI);
context.stroke();
}
}
canvas.addEventListener("mousemove", function(e) {
if (isDone) {
if (draggable) {
mouse = oMousePos(canvas, e);
// draggable - 1 is the index of the point in the coordinates array
coordinates[draggable - 1].x = mouse.x;
coordinates[draggable - 1].y = mouse.y;
drawPolygon();
}
}
});
canvas.addEventListener("mouseup", function(e) {
if (draggable) {
draggable = false;
}
});
// a function to detect the mouse position
function oMousePos(canvas, evt) {
var ClientRect = canvas.getBoundingClientRect();
return {
//objeto
x: Math.round(evt.clientX - ClientRect.left),
y: Math.round(evt.clientY - ClientRect.top)
};
}
canvas {
border: 1px solid black;
}
<canvas id="canvas" width="600" height="600"></canvas>
I also tried to draw my own parallelogram, but can't do it draggable
class Point {
constructor(x, y) {
this.x = x;
this.y = y;
}
startX;
startY;
}
var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");
var cw = canvas.width;
var ch = canvas.height;
var mouse = {};
var draggable = false;
var points = [];
let isDone = false;
var clicks =0;
let click = false;
canvas.addEventListener("click", function(e) {
console.log(clicks);
clicks++;
if(!isDone){
const point = new Point(e.offsetX, e.offsetY);
points.push(point);
context.beginPath();
context.arc(point.x, point.y, 5, 0, 2 * Math.PI);
context.fillStyle = "red";
context.fill();
if(clicks===3){
isDone=true;
}
}
if(isDone){
GetMassCenterAndFourthPoint(points);
drawParallelogramAndCircle();
}
});
function GetMassCenterAndFourthPoint(knownpoints){
const point4X = knownpoints[2].x-knownpoints[1].x+knownpoints[0].x;
const point4Y = knownpoints[2].y-knownpoints[1].y+knownpoints[0].y;
context.beginPath();
context.arc(point4X, point4Y, 5, 0, 2 * Math.PI);
context.fillStyle = "red";
context.fill();
points.push(new Point(point4X, point4Y));
const massCenterX = (knownpoints[1].x+knownpoints[3].x)/2;
const massCenterY = (knownpoints[1].y+knownpoints[3].y)/2;
points.push(new Point(massCenterX, massCenterY));
}
function drawParallelogramAndCircle(){
context.beginPath();
context.moveTo(points[0].x, points[0].y);
for(let i=1;i<points.length-1;i++){
context.lineTo(points[i].x, points[i].y);
if(i===3){
context.lineTo(points[0].x, points[0].y);
}
}
context.strokeStyle = "blue";
context.closePath();
context.stroke();
// find square. Here will be the logic to calculate square
let square = 250;
context.beginPath();
context.arc(points[4].x, points[4].y, 30, 0, 2 * Math.PI);
context.strokeStyle = "yellow";
context.closePath();
context.stroke();
}
canvas {
border: 1px solid black;
}
<canvas id="canvas" width="600" height="600"></canvas>
I am having problems when drawing a circle. How do I clear it?
I also still want to maintain the transparent background as much as possible as I am planning on making particles rain down. I also would want to not use images to lower the load on the server.
var canvas = document.getElementById("canvas");
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
var ctx = canvas.getContext("2d");
const ParticleFactory = function(){
this.interval = 100;
this.lastOutput = Date.now();
this.particles = [];
}
ParticleFactory.prototype.tick = function(){
if (Date.now() > this.lastOutput + this.interval) {
const particle = new Particle(500, 100, 4);
this.particles.push(particle);
this.lastOutput = Date.now();
}
for (var i=0; i < this.particles.length; i++) {
this.particles[i].tick();
};
}
ParticleFactory.prototype.draw = function(){
for (var i=0; i < this.particles.length; i++) {
this.particles[i].draw();
};
}
ParticleFactory.prototype.del = function(toDelete){
this.particles = this.particles.filter(item => item !== toDelete);
}
const Particle = function(x, y, r){
this.x = x;
this.y = y;
this.r = r;
}
Particle.prototype.tick = function(){
this.x -= 0.1;
}
Particle.prototype.draw = function(){
ctx.beginPath();
ctx.arc(this.x, this.y, this.r, 0, 2 * Math.PI, false);
ctx.fillStyle = "rgb(0, 0, 255)";
ctx.fill();
ctx.closePath();
}
// Definitions
let particleFactory = new ParticleFactory;
function draw(){
ctx.clearRect(0, 0, canvas.width, canvas.height);
particleFactory.draw();
}
function tick(){
particleFactory.tick();
draw()
window.requestAnimationFrame(tick)
}
document.addEventListener("DOMContentLoaded", function() {
tick();
});
ctx.clearRect() doesn't clear the curcle that is being draws every tick by Particle.draw()
The dot moves and leaves a trail behind even when ctx.clearRect() is run before every draw.
I am using a canvas element on my web page, and need to be able to draw circles on mouse click with a different color each click. Here is the code I have, which works on some sites but not others. My question is what am I missing for this to work? I know that it only has one color currently in the code, but as it stands, I click all over the canvas and nothing happens.
var canvas = document.getElementById("cirCanvas");
var context = canvas.getContext("2d");
function createImageOnCanvas(imageId) {
canvas.style.display = "block";
document.getElementById("circles").style.overflowY = "hidden";
var img = new Image(300, 300);
img.src = document.getElementById(imageId).src;
context.drawImage(img, (0), (0)); //onload....
}
function draw(e) {
var pos = getMousePos(canvas, e);
posx = pos.x;
posy = pos.y;
context.fillStyle = "#000000";
context.beginPath();
context.arc(posx, posy, 50, 0, 2 * Math.PI);
context.fill();
}
function getMousePos(canvas, evt) {
var rect = canvas.getBoundingClientRect();
return {
x: evt.clientX - rect.left,
y: evt.clientY - rect.top
};
}
window.draw = draw;
<head>
<title></title>
<meta charset="utf-8">
<script src="clickCircle.js"></script>
</head>
<body>
<div id="circles"></div>
<canvas id="cirCanvas" width="250" height="250" onclick="draw (event)">
</canvas>
</body>
Below is example of a random color generator function.
Also you should try add the click event listener in an unobtrusive way.
var canvas = document.getElementById("cirCanvas");
var context = canvas.getContext("2d");
canvas.addEventListener('click', draw, false);
function draw(e) {
var pos = getMousePos(canvas, e);
posx = pos.x;
posy = pos.y;
context.fillStyle = randomColor();
context.beginPath();
context.arc(posx, posy, 50, 0, 2 * Math.PI);
context.fill();
}
function randomColor() {
var color = [];
for (var i = 0; i < 3; i++) {
color.push(Math.floor(Math.random() * 256));
}
return 'rgb(' + color.join(',') + ')';
}
function getMousePos(canvas, evt) {
var rect = canvas.getBoundingClientRect();
return {
x: evt.clientX - rect.left,
y: evt.clientY - rect.top
};
}
#cirCanvas {
border: 1px solid black;
}
<div id="circles">
<canvas id="cirCanvas" width="250" height="250"></canvas>
</div>
Here is how to change color - you can randomize the colors:
Best way to generate a random color in javascript?
or use an array of fixed colors
colors = ["001100","AA0000","00BB00"];
using
context.fillStyle = "#"+colors[Math.round(Math.random()*colors.length)];
Random version:
var canvas = document.getElementById("cirCanvas"),
context = canvas.getContext("2d");
function createImageOnCanvas(imageId) {
canvas.style.display = "block";
document.getElementById("circles").style.overflowY = "hidden";
var img = new Image(300, 300);
img.src = document.getElementById(imageId).src;
context.drawImage(img, (0), (0)); //onload....
}
function draw(e) {
var pos = getMousePos(canvas, e);
posx = pos.x;
posy = pos.y;
context.fillStyle = '#'+(0x1000000+(Math.random())*0xffffff).toString(16).substr(1,6)
context.beginPath();
context.arc(posx, posy, 50, 0, 2 * Math.PI);
context.fill();
}
function getMousePos(canvas, evt) {
var rect = canvas.getBoundingClientRect();
return {
x: evt.clientX - rect.left,
y: evt.clientY - rect.top
};
}
//window.draw = draw;
<div id="circles"></div>
<canvas id="cirCanvas" width="250" height="250" onclick="draw(event)">
</canvas>
You have to implement a function which is able to generate a random color.
just use sth. like this:
function getRandomColor() {
var letters = '0123456789ABCDEF';
var color = '#';
for (var i = 0; i < 6; i++) {
color += letters[Math.floor(Math.random() * 16)];
}
return color;
}
JsFiddle example
I am looking for a way to fillStyle of all circles in 4 colors: #00ce66, #e3bf37, #cc5543, #a1b7c2.
I want circles to show in the way: 25% of circles are red, 25% circles are yellow… etc. on canvas while the page is loaded.
When I added Math.random() and put inside the colors, circles are black. Please help :-)
(function() {
var width, height, largeHeader, canvas, ctx, circles, target, animateHeader = true;
// Main
initHeader();
addListeners();
function initHeader() {
width = window.innerWidth;
height = window.innerHeight;
target = {x: 0, y: height};
largeHeader = document.getElementById('large-header');
largeHeader.style.height = height+'px';
canvas = document.getElementById('canvas');
canvas.width = width;
canvas.height = height;
ctx = canvas.getContext('2d');
// create particles
circles = [];
for(var x = 0; x < width*0.2; x++) {
var c = new Circle();
circles.push(c);
}
animate();
}
// Event handling
function addListeners() {
window.addEventListener('scroll', scrollCheck);
window.addEventListener('resize', resize);
}
function scrollCheck() {
if(document.body.scrollTop > height) animateHeader = false;
else animateHeader = true;
}
function resize() {
width = window.innerWidth;
height = window.innerHeight;
largeHeader.style.height = height+'px';
canvas.width = width;
canvas.height = height;
}
function animate() {
if(animateHeader) {
ctx.clearRect(0,0,width,height);
for(var i in circles) {
circles[i].draw();
}
}
requestAnimationFrame(animate);
}
// Canvas manipulation
function Circle() {
var _this = this;
// constructor
(function() {
_this.pos = {};
init();
console.log(_this);
})();
function init() {
_this.pos.x = Math.random()*width;
_this.pos.y =-50;
_this.alpha = 0.1+Math.random()*0.9;
_this.scale = 0.1+Math.random()*1;
_this.velocity = Math.random();
}
this.draw = function() {
if(_this.alpha <= 0) {
init();
}
_this.pos.y -= -_this.velocity;
_this.alpha -= 0.0005;
ctx.beginPath();
ctx.arc(_this.pos.x, _this.pos.y, _this.scale*10, 0, 2 * Math.PI, false);
ctx.fillStyle = 'rgba(16,239,173,'+ _this.alpha+')';
ctx.fill();
};
}
})();
You can create an array with the 4 colors and choose a random one at the creation of each circle.
Here is code for the Circle function:
function Circle() {
var _this = this;
// constructor
(function() {
_this.pos = {};
init();
console.log(_this);
})();
function init() {
_this.pos.x = Math.random()*width;
_this.pos.y =-50;
_this.alpha = 0.1+Math.random()*0.9;
_this.scale = 0.1+Math.random()*1;
_this.velocity = Math.random();
var colors = [[0,206,102], [227, 191, 55], [204,85,67], [161,183, 194]];
var random_index = Math.floor(0 + (Math.random() * ((3 + 1) - 0)));
_this.color = colors[random_index];
}
this.draw = function() {
if(_this.alpha <= 0) {
init();
}
_this.pos.y -= -_this.velocity;
_this.alpha -= 0.0005;
ctx.beginPath();
ctx.arc(_this.pos.x, _this.pos.y, _this.scale*10, 0, 2 * Math.PI, false);
var c = _this.color;
ctx.fillStyle = 'rgba('+c[0]+','+c[1]+','+c[2]+','+ _this.alpha+')';
ctx.fill();
};
}
I'm trying to set up a background in canvas and have some small circles just flow throughout the background, eventually I'll change the shapes and add more details in, but I'm just having trouble with the set up.
I know my code is janky, but are there any suggestions to the structure of the code?
var dx = 1;
var dy = 2;
var circle=new Circle(400,30,10);
var timer;
function Circle(x,y,r){
this.x=x;
this.y=y;
this.r=r;
}
function init() {
// Get the canvas element.
canvas = document.getElementById("canvas");
if (canvas.getContext) {
ctx = canvas.getContext("2d");
ctx.fillStyle = "black";
}
timer=setInterval(draw, 10);
return timer;
}
function gradient (){
var my_gradient=ctx.createLinearGradient(0,0,1000,0);
my_gradient.addColorStop(0,"black");
my_gradient.addColorStop(1,"white");
ctx.fillStyle=my_gradient;
ctx.fillRect(0,0,1000,1000);
ctx.rect(0, 0, 1000, 1000);
stars();
}
function stars(){
for (i = 0; i <= 50; i++) {
// Get random positions for stars
var x = Math.floor(Math.random() * 1000)
var y = Math.floor(Math.random() * 1000)
ctx.fillStyle = "yellow";
//if (x < 30 || y < 30) ctx.fillStyle = "black";
ctx.beginPath();
ctx.arc(x, y, 3, 0, Math.PI * 2, true);
ctx.closePath();
ctx.fill();
}
}
function move(){
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = gradient.my_gradient;
ctx.fillRect(0,0,canvas.width,canvas.height);
ctx.fillStyle = "#003300";
drawBall(circle);
if (circle.x +dx > canvas.width || circle.x +dx < 0)
dx=-dx;
if(circle.y+dy>bar.y && circle.x>bar.x && circle.x<bar.x+barImg.width)
dy=-dy;
if (circle.y +dy > canvas.height || circle.y +dy < 0)
dy=-dy;
circle.x += dx;
circle.y += dy;
}
I tried to code a working exemple. Here stars are popping up continuously.
HTML
<!DOCTYPE html>
<html>
<head>
<title>Exemple</title>
</head>
<body>
<canvas id="viewport"></canvas>
<script src='test.js'></script>
</body>
</html>
JS
var doc = document;
var canvas = doc.getElementById('viewport');
var ctx = canvas.getContext('2d');
var settings = {
area : {
height : 100,
width : 100
}
};
canvas.width = settings.area.width;
canvas.height = settings.area.height;
function draw() {
for (var i = 10; i--;) {
var x = Math.floor(Math.random() * 1000)
var y = Math.floor(Math.random() * 1000)
ctx.beginPath();
ctx.arc(x, y, 3, 0, Math.PI * 2, true);
ctx.fillStyle = "yellow";
ctx.closePath();
ctx.fill();
}
}
function gameLoop (render, element) {
var running, lastFrame = +new Date;
function loop( now ) {
// stop the loop if render returned false
if ( running !== false ) {
requestAnimationFrame( loop, element );
running = render( now - lastFrame );
lastFrame = now;
}
}
loop( lastFrame );
}
gameLoop (function (deltaT) {
draw();
}, canvas );
Here is the fiddle : https://jsfiddle.net/q4q0uLht/
----- EDIT -----
/*
Basic config
*/
var doc = document,
canvas = doc.getElementById('viewport'),
ctx = canvas.getContext('2d');
var settings = {
canvas: {
height: 200,
width: 300
}
}
canvas.height = settings.canvas.height;
canvas.width = settings.canvas.width;
canvas.style.border = '1px #000 solid';
/*
easy gets a random number, inside a range of [0, x);
*/
function getRandomNumber(x) {
return parseInt(Math.random() * x, 10);
}
/*
Checks if the obj passed in argument is still in the canvas limits
*/
function incorrectPosition(obj) {
return obj.x < 0 || obj.y < 0 || obj.x > settings.canvas.width || obj.y > settings.canvas.height;
}
/*
stars array and Star object.
*/
var stars = [];
function Star(r) {
this.x = getRandomNumber(canvas.width);
this.y = getRandomNumber(canvas.height);
this.r = r || 10;
this.move = function(dx, dy) {
this.x += dx;
this.y += dy;
};
}
/*
This function adds new stars,
calculates new coordinates of each star,
and removes them from the stars array
when they are out of the canvas limits.
*/
function update() {
var len = stars.length;
if (len < 10) {
stars.push(new Star());
}
for (var i = len; i--;) {
var star = stars[i];
star.move(1, 2);
if (incorrectPosition(star)) {
stars.splice(i, 1);
}
}
}
/*
This function clears the canvas each turn and
draws each star which is stored inside the stores array.
*/
function draw() {
ctx.clearRect(0, 0, settings.canvas.width, settings.canvas.height);
var len = stars.length;
for (var i = len; i--;) {
var star = stars[i];
ctx.beginPath();
ctx.arc(star.x, star.y, 3, 0, Math.PI * 2, true);
ctx.fillStyle = "yellow";
ctx.closePath();
ctx.fill();
}
}
// Here is the loop inside which are called functions
setInterval(loop, 33);
function loop() {
update(); // update first
draw(); // then draw
}
<!DOCTYPE html>
<html>
<head>
<title>Exemple</title>
</head>
<body>
<canvas id="viewport"></canvas>
<script src='test.js'></script>
</body>
</html>