line rotation in class javascript canvas - javascript

I try to create a class with a function which might be use to change the angle of a line already drawn.
With what I write, the line doesn't move. When I press the right or left key, I have this error :
TypeError: this.changeAngle is not a function
Indeed, I don't have "function" keyword in my code ... I don't know what to use instead.
Could you help me ?
Thank you very much.
window.onload = init;
let canvas, ctx;
let mousePos;
let angle = 0;
class Lanceur {
constructor() {
this.changeAngle(this.angle);
}
update(ctx) {
this.drawAiguille(ctx);
}
drawSocleLanceur(ctx) {
ctx.save();
ctx.beginPath();
ctx.lineWidth = 2;
ctx.arc(w/2, h, 20, 0, 2 * Math.PI);
ctx.stroke();
ctx.restore();
}
drawAiguille(ctx) {
ctx.save();
ctx.rotate(this.angle);
ctx.strokeStyle = "rgb(255, 0, 0)";
ctx.lineWidth=3;
ctx.beginPath();
ctx.moveTo(w/2, h-h*0.12);
ctx.lineTo(w/2, h-h*0.035);
ctx.stroke();
ctx.restore();
}
changeAngle(a) {
this.angle = a;
}
getAngle() {
return this.angle;
}
}
function init() {
canvas = document.querySelector("#jeu");
ctx = canvas.getContext("2d");
w = canvas.width;
h = canvas.height;
a = new Lanceur();
requestAnimationFrame(mainloop);
}
function mainloop() {
ctx.clearRect(0, 0, w, h);
a.update(ctx);
requestAnimationFrame(mainloop);
}
document.addEventListener('keypress', function(event){
gereTouches(event);
});
function gereTouches(event) {
if(event.key == "ArrowRight") {
this.changeAngle(this.getAngle - 1);
console.log("ça bouge : " + this.angle);
}else if(event.key == "ArrowLeft") {
this.changeAngle(this.getAngle + 1);
}
}

Main changes:
added this.angle to thr constructor()
using keydown event
the function gereTouches(event) uses a instead of this and a.getAngle() instead of a.getAngle
also 1 for the the angle is way too big (those are radians). I'm using .01 instead.
I hope it helps.
window.onload = init;
let canvas, ctx;
let mousePos;
let angle = 0;
class Lanceur {
constructor() {
this.angle = 0;
this.changeAngle(this.angle);
}
update(ctx) {
this.drawAiguille(ctx);
}
drawSocleLanceur(ctx) {
ctx.save();
ctx.beginPath();
ctx.lineWidth = 2;
ctx.arc(w/2, h, 20, 0, 2 * Math.PI);
ctx.stroke();
ctx.restore();
}
drawAiguille(ctx) {
ctx.save();
ctx.rotate(this.angle);
ctx.strokeStyle = "rgb(255, 0, 0)";
ctx.lineWidth=3;
ctx.beginPath();
ctx.moveTo(w/2, h-h*0.12);
ctx.lineTo(w/2, h-h*0.035);
ctx.stroke();
ctx.restore();
}
changeAngle(a) {
this.angle = a;
}
getAngle() {
return this.angle;
}
}
function init() {
canvas = document.querySelector("#jeu");
ctx = canvas.getContext("2d");
w = canvas.width = 500;
h = canvas.height = 500;
a = new Lanceur();
requestAnimationFrame(mainloop);
}
function mainloop() {
ctx.clearRect(0, 0, w, h);
a.update(ctx);
requestAnimationFrame(mainloop);
}
document.addEventListener('keydown', function(event){
gereTouches(event);
});
function gereTouches(event) {
if(event.key == "ArrowRight") {
a.changeAngle(a.getAngle() - .01);
console.log("ça bouge : " + a.angle);
}else if(event.key == "ArrowLeft") {
a.changeAngle(a.getAngle() + .01);
}
}
canvas{border:1px solid}
<canvas id="jeu"></canvas>

Related

Change color inside circle

I want to change color inside circle example:(two color) from red to blue and blue to red.
I tried this using if else but it didn't work for me.
let canvas = document.getElementById("canvas");
let context = canvas.getContext("2d");
// for canvas size
var window_width = window.innerWidth;
var window_height = window.innerHeight;
canvas.width = window_width;
canvas.height = window_height;
let hit_counter = 0;
// object is created using class
class Circle {
constructor(xpos, ypos, radius, speed, color, text) {
this.position_x = xpos;
this.position_y = ypos;
this.radius = radius;
this.speed = speed;
this.dx = 1 * this.speed;
this.dy = 1 * this.speed;
this.text = text;
this.color = color;
}
// creating circle
draw(context) {
context.beginPath();
context.strokeStyle = this.color;
context.fillText(this.text, this.position_x, this.position_y);
context.textAlign = "center";
context.textBaseline = "middle"
context.font = "20px Arial";
context.lineWidth = 5;
context.arc(this.position_x, this.position_y, this.radius, 0, Math.PI * 2);
context.stroke();
context.closePath();
}
update() {
this.text = hit_counter;
context.clearRect(0, 0, window_width, window_height)
this.draw(context);
if ((this.position_x + this.radius) > window_width) {
this.dx = -this.dx;
hit_counter++;
}
if ((this.position_x - this.radius) < 0) {
this.dx = -this.dx;
hit_counter++;
}
if ((this.position_y - this.radius) < 0) {
this.dy = -this.dy;
hit_counter++;
}
if ((this.position_y + this.radius) > window_height) {
this.dy = -this.dy;
hit_counter++;
}
this.position_x += this.dx;
this.position_y += this.dy;
}
}
let my_circle = new Circle(100, 100, 50, 3, 'Black', hit_counter);
let updateCircle = function() {
requestAnimationFrame(updateCircle);
my_circle.update();
}
updateCircle();
//for color
function changeColor(event) {
var coloorr = event.value;
canvas.style.background = coloorr;
}
// I tried it in bllk function but it didn't work for me.
function bllk() {
canvas.style.background = "black";
context.fillStyle = "blue";
// I tried it in bllk function but it didn't work for me.
// setInterval(() => {
// if(context.fillStyle=="blue"){
// context.fillStyle=red;
// context.fill();
// }else if(context.fillStyle=="red"){
// context.fillStyle=blue;
// context.fill();
// }else if(context.fillStyle=="blue"){
// context.fillStyle=red;
// context.fill();
// }
// }, 1000);
}
<!-- On clicking button Hi How to apply two color one by one to the numbers inside the circle ? I tried it in bllk function but it didn't work for me. -->
<button onclick="bllk()">Hi</button>
<canvas id="canvas"></canvas>
The code needed a little upgrade:
decoupling variables from each other & the global space
adding some internal attributes & methods to the circle
Now it's possible to change the background color of the canvas, the outline and text of the circle, and the background of the circle separataley.
const canvas = document.getElementById("canvas");
const context = canvas.getContext("2d");
// for canvas size
const window_width = window.innerWidth;
const window_height = window.innerHeight;
canvas.width = window_width;
canvas.height = window_height;
// object is created using class
class Circle {
constructor(xpos, ypos, radius, speed, color, text) {
this.position_x = xpos;
this.position_y = ypos;
this.radius = radius;
this.speed = speed;
this.dx = 1 * this.speed;
this.dy = 1 * this.speed;
this.text = text;
this.color = color;
this.fillColor = "white" // added as a default value
this.hit_counter = 0
}
// outline & text in circle
drawOutline({
ctx
}) {
ctx.beginPath();
ctx.strokeStyle = this.color;
ctx.fillStyle = this.color
ctx.fillText(this.text, this.position_x, this.position_y);
ctx.textAlign = "center";
ctx.textBaseline = "middle"
ctx.font = "20px Arial";
ctx.lineWidth = 5;
ctx.arc(this.position_x, this.position_y, this.radius, 0, Math.PI * 2);
ctx.stroke();
ctx.closePath();
}
// background of the circle
drawFill({
ctx,
color
}) {
ctx.beginPath();
ctx.fillStyle = this.fillColor
ctx.arc(this.position_x, this.position_y, this.radius, 0, Math.PI * 2);
ctx.fill();
ctx.closePath();
}
// drawing the circle from two pieces
draw(ctx) {
this.drawFill({
ctx
})
this.drawOutline({
ctx
})
}
// color change function
setColor({
outline,
fill
}) {
this.color = outline
this.fillColor = fill
}
update(ctx) {
this.text = this.hit_counter;
ctx.clearRect(0, 0, window_width, window_height)
this.draw(context);
if ((this.position_x + this.radius) > window_width) {
this.dx = -this.dx;
this.hit_counter++;
}
if ((this.position_x - this.radius) < 0) {
this.dx = -this.dx;
this.hit_counter++;
}
if ((this.position_y - this.radius) < 0) {
this.dy = -this.dy;
this.hit_counter++;
}
if ((this.position_y + this.radius) > window_height) {
this.dy = -this.dy;
this.hit_counter++;
}
this.position_x += this.dx;
this.position_y += this.dy;
}
}
const my_circle = new Circle(100, 100, 50, 3, 'Black');
const updateCircle = function(ctx) {
requestAnimationFrame(() => updateCircle(ctx));
my_circle.update(ctx);
}
updateCircle(context);
// I tried it in bllk function but it didn't work for me.
function bllk1() {
canvas.style.background = "black";
my_circle.setColor({
outline: "red",
fill: "yellow"
})
}
function bllk() {
canvas.style.background = "black";
my_circle.setColor({
outline: "black",
fill: "blue"
})
setInterval(() => {
const fill = my_circle.fillColor === "blue" ? "red" : "blue"
my_circle.setColor({
outline: "black",
fill,
})
}, 1000);
}
<!-- On clicking button Hi How to apply two color one by one to the numbers inside the circle ? I tried it in bllk function but it didn't work for me. -->
<button onclick="bllk()">Hi</button>
<canvas id="canvas"></canvas>
I simplified your code to just focus on what you asked on the comments:
changing red to blue and blue to red color continuously
To focus on that specific problem we don't need the Circle moving or the collisions with the borders, in the future when you are asking a question you should do the same, provide a minimal example, remove everything else that is not specifically related to your problem.
To solve your issue we can pass a colors parameter to the draw function, that way we let it know what colors to use for the circle and the text, or anything you might want to add in the future.
See code sample below:
let canvas = document.getElementById("canvas");
let context = canvas.getContext("2d");
canvas.width = canvas.height = 100;
class Circle {
draw(xpos, ypos, radius, colors) {
context.beginPath();
context.arc(xpos, ypos, radius, 0, Math.PI * 2);
context.fillStyle = colors.circle;
context.fill();
context.beginPath();
context.font = "20px Arial";
context.fillStyle = colors.text;
context.fillText("0", xpos, ypos);
}
}
let my_circle = new Circle();
let colors = {text:"red", circle:"blue"};
let updateCircle = function() {
requestAnimationFrame(updateCircle);
context.clearRect(0, 0, canvas.width, canvas.height)
my_circle.draw(50, 50, 20, colors);
}
updateCircle();
setInterval(() => {
if (colors.text == "blue") {
colors = {text:"red", circle:"blue"};
} else {
colors = {text:"blue", circle:"red"};
}
}, 1000);
<canvas id="canvas"></canvas>

Javascript Canvas Movement

I have this movement in my canvas:
Gif
I am trying to move everything but the black-gray square. I have tried many times but i dont know how to get the result i need, the rotation is made like this:
ctx.translate(x, y);
if (or == 'R') {
ctx.rotate(Math.PI / movementSpeed);
}
else if (or == 'L'){
ctx.rotate(-Math.PI / movementSpeed);
}
ctx.translate(-x, -y);
drawRect();
drawRect2();
drawCircle();
And the black-gray square i am trying to not move is made like this:
function drawRect() {
ctx.fillStyle = "#393939";
ctx.fillRect(x-35, y-30, 180, 60);
ctx.stroke();
ctx.fill();
ctx.restore();
}
Code snippet:
<!DOCTYPE html>
<html lang="en">
<head>
<style type="text/css">
#import url('https://fonts.googleapis.com/css2?family=Jost:wght#500&display=swap');
body
{
overflow: hidden;
}
div#cerradura {
position: absolute;
width: 100%;
left:5%;
text-align: center;
font-size: 18px;
}
</style>
</head>
<body>
<div onclick="" id="cerradura">
<canvas id="myCanvas" width="1600" height="800">
</canvas>
</div>
</body>
<script>
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
let tensorAdentro = false;
let movimiento = 500;
let rotacion = 0;
let x = 1100;
let y = 400;
function dibujarGanzua() {
// Ganzúa
ctx.lineWidth = 7;
ctx.strokeStyle = "#595959";
ctx.beginPath();
ctx.moveTo(x, y);
ctx.lineTo(x, y+190);
ctx.stroke();
ctx.restore();
}
function dibujarManija() {
// Rectangulo de la cerradura
ctx.fillStyle = "#393939";
ctx.fillRect(x-35, y-30, 180, 60);
ctx.stroke();
ctx.fill();
ctx.restore();
}
function dibujarCerradura() {
ctx.strokeStyle = "#000000";
// Circulo de la cerradura
ctx.fillStyle = '#909090';
ctx.lineWidth = 2;
ctx.beginPath();
ctx.arc(x, y, 20, 0, 2 * Math.PI);
ctx.stroke();
ctx.fill();
ctx.restore();
// Hueco de la cerradura
ctx.lineWidth = 6;
ctx.beginPath();
ctx.moveTo(x-10, y);
ctx.lineTo(x+10, y);
ctx.stroke();
ctx.restore();
}
function girarGanzua(or) {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.translate(x, y);
if (or == 'R') {
ctx.rotate(Math.PI / movimiento);
rotacion += (((Math.PI / movimiento)*180)/Math.PI);
}
else if (or == 'L'){
ctx.rotate(-Math.PI / movimiento);
rotacion += (-((Math.PI / movimiento)*180)/Math.PI);
}
ctx.translate(-x, -y);
dibujarManija();
dibujarCerradura();
dibujarGanzua();
}
window.addEventListener('mousedown', (e) => {
if (!tensorAdentro && e.button === 0) {
dibujarGanzua();
tensorAdentro = !tensorAdentro;
}
});
// Lee input de mouse
var direction = "",
oldx = 0,
mousemovemethod = function (e) {
dx = e.clientX - oldx;
if (dx < 0 && tensorAdentro) {
if (rotacion <= 90) {
girarGanzua('R')
}
}
else if (dx > 0 && tensorAdentro){
if (rotacion > 0) {
girarGanzua('L')
}
}
oldx = e.clientX;
}
document.addEventListener('mousemove', mousemovemethod);
dibujarManija();
dibujarCerradura();
</script>
</html>
How can i make this happen?
Thanks.
What is happening here is that the context is getting rotated on every mouse move without getting restored to the original state. It would be better to save the context before drawing and restore it when finished drawing. And, to rotate it by the correct angle, just rotate it by rotacion * Math.PI / 180 every time.
function girarGanzua(or) {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.save(); // Save the context
dibujarManija(); // Draw the large Rect before rotating
ctx.translate(x, y);
ctx.rotate(rotacion * Math.PI / 180);
if (or == 'R') {
rotacion += (((Math.PI / movimiento)*180)/Math.PI);
}
else if (or == 'L'){
rotacion += (-((Math.PI / movimiento)*180)/Math.PI);
}
ctx.translate(-x, -y);
dibujarCerradura();
dibujarGanzua();
ctx.restore(); // Restore the context
}
Also, there is no need to restore the context after drawing each entity.
Working Snippet:
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
let tensorAdentro = false;
let movimiento = 500;
let rotacion = 0;
let x = 200;
let y = 200;
function dibujarGanzua() {
// Ganzúa
ctx.lineWidth = 7;
ctx.strokeStyle = "#595959";
ctx.beginPath();
ctx.moveTo(x, y);
ctx.lineTo(x, y+190);
ctx.stroke();
//ctx.restore(); No Need
}
function dibujarManija() {
// Rectangulo de la cerradura
ctx.fillStyle = "#393939";
ctx.fillRect(x-35, y-30, 180, 60);
ctx.stroke();
ctx.fill();
//ctx.restore(); No Need
}
function dibujarCerradura() {
ctx.strokeStyle = "#000000";
// Circulo de la cerradura
ctx.fillStyle = '#909090';
ctx.lineWidth = 2;
ctx.beginPath();
ctx.arc(x, y, 20, 0, 2 * Math.PI);
ctx.stroke();
ctx.fill();
//ctx.restore(); No Need
// Hueco de la cerradura
ctx.lineWidth = 6;
ctx.beginPath();
ctx.moveTo(x-10, y);
ctx.lineTo(x+10, y);
ctx.stroke();
//ctx.restore(); No Need
}
function girarGanzua(or) {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.save();
dibujarManija();
ctx.translate(x, y);
ctx.rotate(rotacion * Math.PI / 180);
if (or == 'R') {
rotacion += (((Math.PI / movimiento)*180)/Math.PI);
}
else if (or == 'L'){
rotacion += (-((Math.PI / movimiento)*180)/Math.PI);
}
ctx.translate(-x, -y);
dibujarCerradura();
dibujarGanzua();
ctx.restore();
}
window.addEventListener('mousedown', (e) => {
if (!tensorAdentro && e.button === 0) {
dibujarGanzua();
tensorAdentro = !tensorAdentro;
}
});
// Lee input de mouse
var direction = "",
oldx = 0,
mousemovemethod = function (e) {
dx = e.clientX - oldx;
if (dx < 0 && tensorAdentro) {
if (rotacion <= 90) {
girarGanzua('R')
}
}
else if (dx > 0 && tensorAdentro){
if (rotacion > 0) {
girarGanzua('L')
}
}
oldx = e.clientX;
}
document.addEventListener('mousemove', mousemovemethod);
dibujarManija();
dibujarCerradura();
#import url('https://fonts.googleapis.com/css2?family=Jost:wght#500&display=swap');
body
{
overflow: hidden;
}
div#cerradura {
position: absolute;
width: 100%;
left:5%;
text-align: center;
font-size: 18px;
}
<div onclick="" id="cerradura">
<canvas id="myCanvas" width="1600" height="800"></canvas>
</div>

"OOP" in canvas correct way

I'm trying to draw something on canvas with sugar code that we received not that long time ago. I'm using babel of course. I have two questions. First of all you can find my code below:
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
class Rectangle {
constructor(x, y) {
this.x = x;
this.y = y;
}
draw() {
ctx.beginPath();
ctx.rect(this.x, this.y, 50, 50);
ctx.fillStyle = "#000";
ctx.fill();
ctx.closePath();
};
move() {
document.addEventListener('keydown', event => {
if (event.keyCode === 37) {
ctx.clearRect(0, 0, canvas.width, canvas.height)
this.x--
this.draw();
}
if (event.keyCode === 39) {
ctx.clearRect(0, 0, canvas.width, canvas.height)
this.x++
this.draw();
}
})
}
}
class Ball {
constructor(x, y) {
this.x = x;
this.y = y;
}
draw() {
ctx.beginPath();
ctx.arc(this.x, this.y, 10, 0, Math.PI*2);
ctx.fillStyle = "#0095DD";
ctx.fill();
ctx.closePath();
};
}
const rect = new Rectangle(130, 50);
const ball = new Ball(60, 40)
setInterval(() => {
rect.draw();
rect.move();
ball.draw();
}, 100);
I made two classes. One is rectangle, second ball. Rectangle is the one that can move with arrows. When i move, ball disapears for a brief second, then appears on the screen again. What am i doing wrong in this case? How game flow should look like properly?
Second question is: how can i make these two classes interract with each other? For example, i want that when rectangle will touch ball simple console.log will apear. Thanks
Most of the code is yours. Since I prefer using requestAnimationFrame I'm adding an identifier for the request: let requestId = null;.
The move() method of the rectangle deals only with the value of x, and takes the key as an attribute.
Also I've written the frame function that builds your animation frame by frame.
function frame() {
requestId = window.requestAnimationFrame(frame);
ctx.clearRect(0, 0, canvas.width, canvas.height);
rect.move(key);
rect.draw();
ball.draw();
}
On keydown you change the value for the key variable, you cancel the current animation, and you call the frame function to start a new animation.
I've added as well a keyup event to stop the animation on key up.
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
let key;
let requestId = null;
class Rectangle {
constructor(x, y) {
this.x = x;
this.y = y;
}
draw() {
ctx.beginPath();
ctx.rect(this.x, this.y, 50, 50);
ctx.fillStyle = "#000";
ctx.fill();
//ctx.closePath();
}
move(key) {
if (key == 37) {
this.x--;
}
if (key == 39) {
this.x++;
}
}
}
class Ball {
constructor(x, y) {
this.x = x;
this.y = y;
}
draw() {
ctx.beginPath();
ctx.arc(this.x, this.y, 10, 0, Math.PI * 2);
ctx.fillStyle = "#0095DD";
ctx.fill();
//ctx.closePath();
}
}
const rect = new Rectangle(130, 50);
const ball = new Ball(60, 40);
rect.draw();
ball.draw();
function frame() {
requestId = window.requestAnimationFrame(frame);
ctx.clearRect(0, 0, canvas.width, canvas.height);
rect.move(key);
rect.draw();
ball.draw();
}
document.addEventListener("keydown", event => {
if (requestId) {
window.cancelAnimationFrame(requestId);
}
key = event.keyCode;
frame();
});
document.addEventListener("keyup", event => {
if (requestId) {
window.cancelAnimationFrame(requestId);
}
});
canvas{border:1px solid;}
<canvas id="myCanvas"></canvas>
PS: Please read this article requestAnimationFrame for Smart Animating

Canvas.Context Restore on mousemove is failing HTML5

I'm trying to create a hover effect for a canvas image when a mousemove over the image, a transparent overlay shows up. Once a user mouseout am trying to restore the canvas back to it initial stage by making use of the Canvas restore method but it keeps failing. Below is the whole code
var images = [];
var halfCircle;
var ctx;
var canvas;
var effect = true;
jQuery(document).ready(function() {
canvas = document.getElementById("myCanvas");
canvas.style.backgroundColor = '#fafafa';
ctx = canvas.getContext("2d");
halfCircle = new HalfCircle();
halfCircle.doArch(ctx);
placeImages(ctx);
addEventListenersToCanvas(canvas, ctx);
});
function placeImages(ctx){
first_image = new Image();
first_image.src = 'http://example.com/media/features/0.png';
first_image.onload = function(){
ctx.drawImage(first_image, 20, 20);
images.push({x:20,y:20,link: "http://example.com/shoppinglist-infographic", img : first_image});
ctx.save();
}
second_image = new Image();
second_image.src = "http://example.com/media/features/1.png";
second_image.onload = function(){
ctx.drawImage(second_image, 130, 150);
images.push({x:130,y:150,link: "http://example.com/referral/invite?g=banner", img : second_image});
ctx.save();
}
third_image = new Image();
third_image.src = "http://example.com/media/features/2.png";
third_image.onload = function(){
ctx.drawImage(third_image, 230, 220);
images.push({x:230,y:220,link: "http://example.com/all-fast-delivery/", img : third_image});
ctx.save();
}
fourth_image = new Image();
fourth_image.src = "http://example.com/media/features/3.png";
fourth_image.onload = function(){
ctx.drawImage(fourth_image,460, 220);
images.push({x:460,y:220,link:"http://example.com/busyhomemaker/", img : fourth_image});
ctx.save();
}
fifth_image = new Image();
fifth_image.src = "http://example.com/media/features/4.png";
fifth_image.onload = function(){
ctx.drawImage(fifth_image,570, 150);
images.push({x:570,y:150,link:"#", img: fifth_image});
ctx.save();
}
sixth_image = new Image();
sixth_image.src = "http://example.com/media/features/5.png";
sixth_image.onload = function(){
ctx.drawImage(sixth_image,620, 20);
images.push({x:620,y:20,link:"#", img:sixth_image});
ctx.save();
}
text_image = new Image();
text_image.src = "http://example.com/media/features/text.png";
text_image.onload = function(){
ctx.drawImage(text_image,285, 20);
ctx.save();
}
}
function getMousePos(canvas, evt) {
var rect = canvas.getBoundingClientRect();
return {
x: evt.clientX - rect.left,
y: evt.clientY - rect.top
};
}
function addEventListenersToCanvas(canvas, ctx){
ctx.save();
canvas.addEventListener('mousemove', function(evt) {
var mousePos = getMousePos(canvas, evt);
for(var i = 0; i < images.length; i++){
if( (mousePos.x > images[i].x) && (mousePos.x < (images[i].x + images[i].img.width)) &&
(mousePos.y > images[i].y) && (mousePos.y < (images[i].y + images[i].img.height))
){
document.body.style.cursor = "pointer";
if(effect) {
ctx.fillStyle = "#fafafa";
ctx.globalAlpha = 0.1;
ctx.fillRect(images[i].x, images[i].y, images[i].img.width, images[i].img.height);
effect = false;
}
}else{
document.body.style.cursor = "auto";
ctx.restore();
effect = true;
}
}
});
//
canvas.addEventListener('click', function(event){
var mousePos = getMousePos(canvas, event);
for(var i = 0; i < images.length; i++){
if(
(mousePos.x > images[i].x) && (mousePos.x < images[i].x + images[i].img.width) &&
(mousePos.y > images[i].y) && (mousePos.y < images[i].y + images[i].img.height)
){
// console.log('clicking on: ' + images[i].link);
window.open(images[i].link);
}
}
});
}
var HalfCircle = function(){
this.numOfArch = 6;
this.posX = 438;
this.posY = 20;
this.rad = 170;
this.color = [
{ start_color: 'rgb(255,182,54)', end_color: 'rgb(255,220,159)' },
{ start_color: 'rgb(240,97,38)', end_color: 'rgb(249,166,57)' },
{ start_color: 'rgb(254,107,108)', end_color: 'rgb(250,74,78)' },
{ start_color: 'rgb(0,131,195)', end_color: 'rgb(0,150,219)' },
{ start_color: 'rgb(115,174,14)', end_color: 'rgb(214,243,137)' },
{ start_color: 'rgb(133,29,250)', end_color: 'rgb(203,159, 255)' },
];
this.lineWidth = 5;
};
HalfCircle.prototype = {
smallDot: function (posX, posY, ctx, colr){
ctx.beginPath();
ctx.fillStyle = colr;
ctx.arc(posX, posY, 7, 0, Math.PI*2, false);
ctx.fill();
ctx.closePath();
},
bigDot : function (posX, posY, ctx, colr){
ctx.beginPath();
ctx.fillStyle = colr;
ctx.arc(posX, posY, 10, 0, Math.PI*2, false);
ctx.fill();
ctx.closePath();
},
getEndCord: function(startCord){
return startCord + Math.PI/this.numOfArch;
},
doArch : function (ctx){
var startCord = 0;
for( i = 0; i < this.numOfArch; i++ ){
dotStartX = this.rad * Math.cos(startCord) + this.posX;
dotStartY = this.rad * Math.sin(startCord) + this.posY;
this.smallDot(dotStartX, dotStartY, ctx , this.color[i].start_color);
ctx.lineWidth = this.lineWidth;
ctx.beginPath();
ctx.strokeStyle = this.color[i].start_color;
var endCord = this.getEndCord(startCord);
ctx.arc(this.posX, this.posY, this.rad, startCord, endCord , false);
ctx.stroke();
ctx.closePath();
startCord = endCord;
dotStartX = this.rad * Math.cos(endCord) + this.posX;
dotStartY = this.rad * Math.sin(endCord) + this.posY;
this.bigDot(dotStartX, dotStartY, ctx , this.color[i].end_color);
}
}
}
Am seriously would need someone input on these. Thanks
context.save only saves the context state (stylings, transformations, etc). It does not save anything you have drawn on the canvas. So context.restore will only restore the context state, not the drawings.
To remove something you have previously drawn on the canvas, you must clear the entire canvas and redraw everything that you do want on the canvas.
Here's example code and a Demo:
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var cw=canvas.width;
var ch=canvas.height;
function reOffset(){
var BB=canvas.getBoundingClientRect();
offsetX=BB.left;
offsetY=BB.top;
}
var offsetX,offsetY;
reOffset();
window.onscroll=function(e){ reOffset(); }
window.onresize=function(e){ reOffset(); }
//
var halfCircle;
var effect = true;
var overlayIndex=-1;
//
var images = [];
images.push({x:20,y:20, link: "http://example.com/shoppinglist-infographic"});
images.push({x:130,y:150,link: "http://example.com/referral/invite?g=banner"});
images.push({x:230,y:220,link: "http://example.com/all-fast-delivery/"});
images.push({x:460,y:220,link:"http://example.com/busyhomemaker/"});
images.push({x:570,y:150,link:"#"});
images.push({x:620,y:20, link:"#"});
images.push({x:285,y:20, link:"#"});
// Define HalfCircle
var HalfCircle = function(){
this.numOfArch = 6;
this.posX = 438;
this.posY = 20;
this.rad = 170;
this.color = [
{ start_color: 'rgb(255,182,54)', end_color: 'rgb(255,220,159)' },
{ start_color: 'rgb(240,97,38)', end_color: 'rgb(249,166,57)' },
{ start_color: 'rgb(254,107,108)', end_color: 'rgb(250,74,78)' },
{ start_color: 'rgb(0,131,195)', end_color: 'rgb(0,150,219)' },
{ start_color: 'rgb(115,174,14)', end_color: 'rgb(214,243,137)' },
{ start_color: 'rgb(133,29,250)', end_color: 'rgb(203,159, 255)' },
];
this.lineWidth = 5;
};
//
HalfCircle.prototype = {
smallDot: function (posX, posY, ctx, colr){
ctx.beginPath();
ctx.fillStyle = colr;
ctx.arc(posX, posY, 7, 0, Math.PI*2, false);
ctx.fill();
ctx.closePath();
},
bigDot : function (posX, posY, ctx, colr){
ctx.beginPath();
ctx.fillStyle = colr;
ctx.arc(posX, posY, 10, 0, Math.PI*2, false);
ctx.fill();
ctx.closePath();
},
getEndCord: function(startCord){
return startCord + Math.PI/this.numOfArch;
},
doArch : function (ctx){
var startCord = 0;
for( i = 0; i < this.numOfArch; i++ ){
dotStartX = this.rad * Math.cos(startCord) + this.posX;
dotStartY = this.rad * Math.sin(startCord) + this.posY;
this.smallDot(dotStartX, dotStartY, ctx , this.color[i].start_color);
ctx.lineWidth = this.lineWidth;
ctx.beginPath();
ctx.strokeStyle = this.color[i].start_color;
var endCord = this.getEndCord(startCord);
ctx.arc(this.posX, this.posY, this.rad, startCord, endCord , false);
ctx.stroke();
ctx.closePath();
startCord = endCord;
dotStartX = this.rad * Math.cos(endCord) + this.posX;
dotStartY = this.rad * Math.sin(endCord) + this.posY;
this.bigDot(dotStartX, dotStartY, ctx , this.color[i].end_color);
}
}
}
// preload all images
// put the paths to your images in imageURLs[]
var imageURLs=[];
imageURLs.push('http://example.com/media/features/0.png');
imageURLs.push('http://example.com/media/features/1.png');
imageURLs.push('http://example.com/media/features/2.png');
imageURLs.push('http://example.com/media/features/3.png');
imageURLs.push('http://example.com/media/features/4.png');
imageURLs.push('http://example.com/media/features/5.png');
imageURLs.push('http://example.com/media/features/text.png');
//
// the loaded images will be placed in imgs[]
var imgs=[];
var imagesOK=0;
startLoadingAllImages(imagesAreNowLoaded);
//
// Create a new Image() for each item in imageURLs[]
// When all images are loaded, run the callback (==imagesAreNowLoaded)
function startLoadingAllImages(callback){
// iterate through the imageURLs array and create new images for each
for (var i=0; i<imageURLs.length; i++) {
// create a new image an push it into the imgs[] array
var img = new Image();
imgs.push(img);
// when this image loads, call this img.onload
img.onload = function(){
// this img loaded, increment the image counter
imagesOK++;
// if we've loaded all images, call the callback
if (imagesOK>=imageURLs.length ) {
callback();
}
};
// notify if there's an error
img.onerror=function(){alert("image load failed");}
// set img properties
img.src = imageURLs[i];
}
}
//
function imagesAreNowLoaded(){
// the imgs[] array now holds fully loaded images
// the imgs[] are in the same order as imageURLs[]
halfCircle = new HalfCircle();
draw();
$("#canvas").mousemove(function(e){handleMouseMove(e);});
}
function draw(){
ctx.fillStyle='#fafafa';
ctx.fillRect(0,0,cw,ch);
halfCircle.doArch(ctx);
for(var i=0;i<imgs.length;i++){
ctx.drawImage(imgs[i], images[i].x,images[i].y);
if(i==overlayIndex){
ctx.fillStyle = "#fafafa";
ctx.globalAlpha = 0.35;
ctx.fillRect( images[i].x, images[i].y, imgs[i].width, imgs[i].height);
ctx.globalAlpha = 1.00;
}
}
}
function handleMouseMove(e){
// tell the browser we're handling this event
e.preventDefault();
e.stopPropagation();
mx=parseInt(e.clientX-offsetX);
my=parseInt(e.clientY-offsetY);
//
overlayIndex=-1;
for(var i=0;i<images.length;i++){
var img=images[i];
var image=imgs[i];
if(
mx>img.x && mx<img.x+image.width &&
my>img.y && my<img.y+image.height
){
overlayIndex=i;
}
}
draw();
}
body{ background-color: ivory; }
#canvas{border:1px solid red; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<canvas id="canvas" width=900 height=500></canvas>
hope it will helps you..
<!doctype html>
<html>
<head>
<meta charset="UTF-8" />
<title>Canvas Test</title>
</head>
<body>
<header> </header>
<nav> </nav>
<section>
<div>
<canvas id="canvas" width="320" height="200">
This text is displayed if your browser does not support HTML5 Canvas.
</canvas>
</div>
<script type="text/javascript">
var canvas;
var ctx;
function init() {
canvas = document.getElementById("canvas");
ctx = canvas.getContext("2d");
draw();
}
function draw() {
ctx.fillStyle = '#FA6900';
ctx.shadowOffsetX = 5;
ctx.shadowOffsetY = 5;
ctx.shadowBlur = 4;
ctx.shadowColor = 'rgba(204, 204, 204, 0.5)';
ctx.fillRect(0,0,15,150);
ctx.save();
ctx.fillStyle = '#E0E4CD';
ctx.shadowOffsetX = 10;
ctx.shadowOffsetY = 10;
ctx.shadowBlur = 4;
ctx.shadowColor = 'rgba(204, 204, 204, 0.5)';
ctx.fillRect(30,0,30,150);
ctx.save();
ctx.fillStyle = '#A7DBD7';
ctx.shadowOffsetX = 15;
ctx.shadowOffsetY = 15;
ctx.shadowBlur = 4;
ctx.shadowColor = 'rgba(204, 204, 204, 0.5)';
ctx.fillRect(90,0,45,150);
ctx.save();
ctx.restore();
ctx.beginPath();
ctx.arc(185, 75, 22, 0, Math.PI*2, true);
ctx.closePath();
ctx.fill();
ctx.restore();
ctx.beginPath();
ctx.arc(260, 75, 15, 0, Math.PI*2, true);
ctx.closePath();
ctx.fill();
ctx.restore();
ctx.beginPath();
ctx.arc(305, 75, 8, 0, Math.PI*2, true);
ctx.closePath();
ctx.fill();
}
init();
</script>
</section>
<aside> </aside>
<footer> </footer>
</body>
</html>

Agario in JavaScript - Player not Moving

I am having problem with my code,
// JavaScript Document
var canvas = document.getElementById("PlayingArea");
var ctx = canvas.getContext("2d");
var canvasWidth = canvas.width;
var canvasHeight = canvas.height;
var foodArray = [];
var size = 10;
var food;
var player1 = {x:150, y:150};
//create Player1
ctx.beginPath();
ctx.arc(150, 150, size, 0, Math.PI * 2);
ctx.fillStyle = "black";
ctx.fill();
function update() {
"use strict";
//BG Refresh
ctx.fillStyle = "white";
ctx.fillRect(0,0,canvasWidth,canvasHeight);
ctx.strokeStyle = "black";
ctx.strokeRect(0,0,canvasWidth,canvasHeight);
document.addEventListener("keydown", Player1Control);
function Player1Control(){
if(event.keyCode === 38) {
player1.y--;
}
if(event.keyCode === 40) {
player1.y++;
}
if(event.keyCode === 39) {
player1.x++;
}
if(event.keyCode === 37) {
player1.x--;
}
}
if (player1.x >= canvasWidth) {
player1.x = canvasWidth;
} else if (player1.x <= 5) {
player1.x = 5;
}
if (player1.y > canvasHeight) {
player1.y = canvasHeight;
} else if (player1.y <= 5) {
player1.y = 5;
}
//Player Show
ctx.beginPath();
ctx.arc(player1.x, player1.y, size, 0, Math.PI * 2);
ctx.fillStyle = "black";
ctx.fill();
//Food Show
for(var i=foodArray.length; i>0; i--){
ctx.beginPath();
ctx.arc({x:foodArray[i].x},{y:foodArray[i].y} , size, 0, Math.PI * 2);
ctx.fill();
}
setTimeout(update, 10);
}
function foodGen(){
"use strict";
food = {x:Math.round(Math.random()*(canvasWidth)),
y:Math.round(Math.random()*(canvasHeight))};
ctx.beginPath();
ctx.arc(food.x, food.y, 5, 0, Math.PI * 2);
ctx.fillStyle = "black";
ctx.fill();
foodArray.push({x:1,y:1});
setTimeout(foodGen, 1000);
}
update();
foodGen(0,750);
The player is not show in my code and I do not know why my player isn't Moving.
I am pretty new at JavaScript and HTML/CSS. This is my first time Stack overflow so I am sorry for any derps.
-lt1489
edit: My player now appears on the screen, can't be moved.
Link: https://jsfiddle.net/5os0qrhp/2/
The original question was answered with the following comment:
Since you don't change fillStyle between clearing the canvas and drawing the player, you are drawing the player white. Since it is white on white, you cannot see the player.
Regarding the second issue, move document.addEventListener and Player1Control to outside update. Additionally, Player1Control needs event as an argument, resulting in:
document.addEventListener("keydown", Player1Control);
function Player1Control(event) { ... }
function update() { ... }
A few syntax changes fixes the code. See jsfiddle to see those changes outlined.

Categories

Resources