I have the code below. What I want to do is instead of a small square to move around the canvas, I want to use an image instead. In my snippet, I tried to use the drawImage function so that I could display the image I want to use. I was able to display the image but when I try to use the WASD keys, it does not move. Instead, the black square is still the one that is being controlled by the keys. Is there a way on how I can control the image using WASD keys and not the black square?
var canvas;
var context;
var ctx;
var xaxis = 10;
var yaxis = 10;
var obstacle = [];
window.onload = function() {
canvas = document.getElementById("textbox");
context = canvas.getContext("2d");
ctx = canvas.getContext("2d");
player.img.src = 'https://64.media.tumblr.com/tumblr_lkl5spPdno1qfamg6.gif'; //
canvas.width = 400;
canvas.height = 400;
drawCanv();
}
/* obstacle object */
var object = {
height: 50,
width: 50,
x: 100,
y: 100,
}
/* player object */
var player = {
height: 10,
width: 10,
img: new Image() //
};
function drawCanv() {
/* canvas */
context.beginPath();
context.fillStyle = "#ffffff";
context.fillRect(0, 0, canvas.width, canvas.height);
/* player */
context.beginPath();
context.fillStyle = "black";
context.drawImage(player.img, player.height, player.width, 10, 10); //
context.fillRect(xaxis, yaxis, player.width, player.height);
/* obstacle object */
var ndx = obstacle.push({
x: object.x,
y: object.y,
width: object.width,
height: object.height,
}) - 1;
ctx.beginPath();
ctx.fillStyle = "red";
ctx.fillRect(obstacle[ndx].x, obstacle[ndx].y, obstacle[ndx].width, obstacle[ndx].height);
}
function hitObsta(player, array) {
for (var value of array) {
if ((player.x + player.width > value.x && player.x < value.x + value.width)
&& (player.y + player.height > value.y && player.y < value.y + value.height)) {
return true;
}
}
return false;
}
function onkeydown(e) {
/* Going right*/
if (e.keyCode == 68 && xaxis + 10 < canvas.width) {
xaxis++;
var updatedCoords = (Object.assign({
x: xaxis,
y: yaxis,
}, player));
if (hitObsta(updatedCoords, obstacle)) {
xaxis--;
}
}
/* Going left*/
else if (e.keyCode == 65 && xaxis > 0) {
xaxis--;
var updatedCoords = (Object.assign({
x: xaxis,
y: yaxis,
}, player));
if (hitObsta(updatedCoords, obstacle)) {
xaxis++;
}
}
/* Going up*/
else if (e.keyCode == 87 && yaxis > 0) {
yaxis--;
var updatedCoords = (Object.assign({
x: xaxis,
y: yaxis,
}, player));
if (hitObsta(updatedCoords, obstacle)) {
yaxis++;
}
}
/* Going down*/
else if (e.keyCode == 83 && yaxis + 10 < canvas.height) {
yaxis++;
var updatedCoords = (Object.assign({
x: xaxis,
y: yaxis,
}, player));
if (hitObsta(updatedCoords, obstacle)) {
yaxis--;
}
}
//render();
drawCanv();
}
function render()
{
context.clearRect(0, 0, canvas.width, canvas.height);
context.drawImage(player.img, player.height, player.width, 10, 10); //
}
window.addEventListener("keydown", onkeydown);
<html>
<head>
<title>Canvas</title>
<style>
</style>
</head>
<body>
<canvas id="textbox" style="border: 1px solid black"></canvas>
<script src="js/app.js"></script>
</body>
</html>
You don't need the black square at all. You can just do something like this:
const image = new Image(10, 10)
image.src = 'https://64.media.tumblr.com/tumblr_lkl5spPdno1qfamg6.gif';
/* player object */
var player = {
height: 10,
width: 10,
img: image
};
function drawCanv() {
// ...
/* player */
context.beginPath();
context.drawImage(player.img, xaxis, yaxis, 10, 10); //
// ...
}
Related
I am relatively new to JavaScript, and am looking to create a platformer game for a class project. I have tried multiple ways to make a player rectangle collide with an obstacle rectangle but none have worked the way I intended. This method that I wrote myself is not functioning at all, and I have no clue why.
var ctx = myCanvas.getContext("2d");
var fps = 50
var level = 1
var gravity = 0.5
var player = {
x: 0,
y: 0,
x_v: 0,
y_v: 0,
width: 20,
height: 20,
speed: 3,
jump: 10,
color: "blue"
}
const obstacle = {
x: 0,
y: 550,
width: 600,
height: 100,
color: "black"
}
function MyKeyUpHandler(MyEvent) {
if (MyEvent.keyCode == 37 || MyEvent.keyCode == 39) {
player.x_v = 0
}; // not left or right
if (MyEvent.keyCode == 38 || MyEvent.keyCode == 40) {
player.y_v = 0
}; // not up or down
}
function MyKeyDownHandler(MyEvent) {
if (MyEvent.keyCode == 37) {
player.x_v = -player.speed
}; // left
if (MyEvent.keyCode == 38) {
player.y_v = -player.jump
}; // up
if (MyEvent.keyCode == 39) {
player.x_v = player.speed
}; // right
MyEvent.preventDefault();
}
function renderplayer() {
player.y_v = player.y_v + gravity
player.x = player.x + player.x_v
player.y = player.y + player.y_v
ctx.fillStyle = player.color
ctx.fillRect(player.x, player.y, player.width, player.height)
}
function renderobstacle() {
ctx.fillStyle = obstacle.color
ctx.fillRect(obstacle.x, obstacle.y, obstacle.width, obstacle.height)
}
function collision() {
if (player.y == obstacle.y - player.height) {
player.y_v = 0
}
}
function frameyshit() {
ctx.clearRect(0, 0, 600, 600)
renderplayer();
renderobstacle();
collision();
if (player.y >= 600) {
player.y = 1
player.x = 1
player.y_v = 0
}
}
setInterval(frameyshit, 1000 / fps)
addEventListener("keydown", MyKeyDownHandler)
addEventListener("keyup", MyKeyUpHandler)
<canvas id=myCanvas width=600 height=600 style="background-color: transparent;"> </canvas>
I really wanna know how to make 2d camera movement in html and javascript, so i wrote this code which is just a character and a block so i can test if the camera movement is working. This is my code:
var c = document.getElementById("screen");
var ctx = c.getContext("2d");
var rightPressed;
var leftPressed;
var x = (c.width - 75) / 2;
var speed = 10;
function block() {
ctx.fillStyle = "#fff";
ctx.fillRect(390, 225, 80, 25);
}
function character() {
ctx.fillStyle = "#00f"
ctx.fillRect(x, 250, 50, 50);
}
function keyUpHandler(event) {
if (event.keyCode == 37) {
leftPressed = false;
} else if (event.keyCode == 39) {
rightPressed = false;
}
}
function keyDownHandler(event) {
if (event.keyCode == 37) {
leftPressed = true;
} else if (event.keyCode == 39) {
rightPressed = true;
}
}
document.addEventListener("keyup", keyUpHandler, false);
document.addEventListener("keydown", keyDownHandler, false);
function draw() {
ctx.clearRect(0, 0, c.width, c.height);
block();
character();
if (rightPressed && (x + 50) < c.width) {
x += speed;
} else if (leftPressed && x > 0) {
x -= speed;
}
requestAnimationFrame(draw);
}
requestAnimationFrame(draw);
#screen {
display: block;
margin: auto;
background-color: #0f0;
border: 2px solid black;
}
#headline {
text-align: center;
}
<h1 id="headline">2d Camera movement</h1>
<canvas id="screen" width="500" height="300"></canvas>
Is there anyone who knows how to do this then please tell me, also it would be nice if you could put it into this code :)
I created two classes, a Game and a Ball. The balls will move when a player presses the left or right key.
The balls know their own position and speed, the game does not care.
Just tell the ball to update according to the game's current state.
I adapted a good portion of code from here:
"Quick Tip: How to Make a Game Loop in JavaScript"
I added ES6 classes, vector support and dynamic game element support.
Demo
const canvasTxt = window.canvasTxt.default;
const KeyCodeMap = {
37: 'left',
38: 'up',
39: 'right',
40: 'down',
65: 'left',
68: 'right',
83: 'down',
87: 'up'
};
Object.assign(canvasTxt, {
align: 'left',
vAlign: 'top',
font: 'monospace',
fontSize: 24
});
const main = () => {
Game.DEBUG = true; // Enable global DEBUG mode.
const ctx = document.getElementById('screen').getContext('2d');
const game = new Game(ctx);
game.gameElements.push(...[
new Ball({
speed: new Victor(10, 0),
position: new Victor(game.getWidth() / 2, game.getHeight() / 2),
color: 'red',
size: 20
}),
new Ball({
speed: new Victor(20, 0),
position: new Victor(game.getWidth() / 2, game.getHeight() / 4),
color: 'green',
size: 30
}),
new Ball({
speed: new Victor(20, 50),
position: new Victor(100, 140),
color: 'cyan',
size: 25
}),
]);
game.redraw();
};
class Ball {
constructor(options) {
let opts = Object.assign({}, Ball.defaultOptions, options);
this.position = opts.position;
this.speed = opts.speed;
this.size = opts.size;
this.color = opts.color;
}
update(container, state) {
if (state.pressedKeys.left && !state.pressedKeys.right) {
this.position.subtract(this.speed);
}
if (state.pressedKeys.right && !state.pressedKeys.left) {
this.position.add(this.speed);
}
this.checkBounds(container); // Make sure object is in-bounds...
}
checkBounds(container) {
if (this.position.x > container.width) {
this.position.x = 0;
}
if (this.position.x < 0) {
this.position.x = container.width;
}
if (this.position.y > container.height) {
this.position.y = 0;
}
if (this.position.y < 0) {
this.position.y = container.height;
}
}
draw(ctx) {
ctx.save();
ctx.beginPath();
ctx.arc(this.position.x, this.position.y, this.size / 2, 0, 2 * Math.PI, false);
ctx.fillStyle = this.color;
ctx.fill();
//ctx.lineWidth = 1;
//ctx.strokeStyle = '#000000';
ctx.stroke();
ctx.restore();
}
}
Ball.defaultOptions = {
position: new Victor(0, 0),
speed: new Victor(0, 0),
size: 1,
color: '#FFFFFF'
};
class Game {
constructor(ctx) {
this.ctx = ctx;
this.gameElements = [];
this.resize();
this.state = {
pressedKeys: {} // Capture key pressed
};
this.__lastRender = 0;
this.__animationId = null;
window.onresize = (e) => this.resize(e);
document.addEventListener('click', (e) => this.clickHandler(e), false);
document.addEventListener('keyup', (e) => this.keyUpHandler(e), false);
document.addEventListener('keydown', (e) => this.keyDownHandler(e), false);
}
clickHandler(e) {
this.isRunning() ? this.pause() : this.run(); // Pause, if running
}
keyUpHandler(event) {
let key = KeyCodeMap[event.keyCode];
delete this.state.pressedKeys[key];
}
keyDownHandler(event) {
let key = KeyCodeMap[event.keyCode];
if (key) this.state.pressedKeys[key] = true;
}
getWidth() {
return this.ctx.canvas.width;
}
getHeight() {
return this.ctx.canvas.height;
}
resize(event) {
this.ctx.canvas.width = window.innerWidth * 2
this.ctx.canvas.height = window.innerHeight * 2
}
update(progress) {
this.gameElements.forEach(gameElement => gameElement.update(this.ctx.canvas, this.state));
}
redraw() {
this.ctx.clearRect(0, 0, this.getWidth(), this.getHeight());
this.gameElements.forEach(gameElement => gameElement.draw(this.ctx));
if (Game.DEBUG) {
this.__renderDebugText(this.ctx);
}
}
/* #private */ __renderDebugText(ctx) {
ctx.save();
let text = 'DEBUG OUTPUT:\n\n' + JSON.stringify(Object.assign({
running: this.isRunning()
}, this.state), null, 2);
let offset = { x: 16, y: 16 };
let bounds = { width: 280, height: 320 };
ctx.fillStyle = 'rgba(16, 16, 16, 0.8)';
ctx.fillRect(offset.x, offset.y, bounds.width, bounds.height);
ctx.lineWidth = 1;
ctx.strokeStyle = '#333';
ctx.strokeRect(offset.x, offset.y, bounds.width, bounds.height);
ctx.fillStyle = '#FFF';
canvasTxt.drawText(ctx, text, offset.x + 4, offset.y + 4, bounds.width, bounds.height);
ctx.restore();
}
loop(timestamp) {
this.update(timestamp - this.__lastRender);
this.redraw();
this.__lastRender = timestamp;
this.__animationId = window.requestAnimationFrame((ts) => this.loop(ts));
}
isRunning() {
return this.__animationId != null;
}
run() {
this.__animationId = window.requestAnimationFrame((ts) => this.loop(ts));
}
pause() {
cancelAnimationFrame(this.__animationId);
this.__animationId = null;
this.redraw();
}
}
Game.DEBUG = false; // Default is off
main();
html,
body {
margin: 0;
padding: 0;
}
canvas {
background: #000;
height: 100%;
width: 100%;
display: block
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/victor/1.1.0/victor.min.js"></script>
<script src="https://unpkg.com/canvas-txt#2.0.6/build/index.js"></script>
<canvas id="screen" />
I have a game, and in it there is a main, controllable character and then enemies that shoot back at the character. For the enemies, when they shoot back I want them to shoot at intervals so that it isn't just one massive block of bullets, and it worked with a setInterval for one, but when a second enemy comes in they don't shoot. Only one of the two will. If anybody has a solution that would be great!
function enemies() {
if (enemy_soldiers.length == 0) {
level += 0.2;
for (var i = 0; i<(1 + Math.floor(Math.round(level))); i++) {
var gx = 1450
var gy = getRandom(430, 630);
enemy_soldiers.push({
x: gx,
y: gy,
l: gl,
d: getRandom(350, 600),
shooting: false,
interval: setInterval (function() {enemy.shooting = true;},fire_rate),
shoot: function() {
enemy_bullets.push({
x: enemy.x+40,
y: enemy.y+87,
vel: 10,
});
}
});
}
}
var enemy;
gctx.clearRect(0, 0, 1400, 800);
for (var i in enemy_soldiers) {
enemy = enemy_soldiers[i];
drawenemy(enemy.x, enemy.y, enemy.l);
//ai
if (distance(enemy.x, enemy.y, cx, cy) >= enemy.d && enemy.x>cx) {
enemy.x-=vel;
}
else if (distance(enemy.x, enemy.y, cx, cy) >= enemy.d && enemy.x<cx) {
enemy.x+=vel;
}
if (distance(enemy.x, enemy.y, cx, cy) <= 600) {
if (enemy.shooting == true) {
enemy.shoot(enemy.x,enemy.y);
enemy.shooting = false;
}
gbctx.clearRect(0, 0, 1400, 800);
for (var j in enemy_bullets) {
enemy_bullet = enemy_bullets[j];
enemy_bullet.x -= enemy_bullet.vel;
if (enemy_bullet.x > 1400 || enemy_bullet.x < -5 || enemy_bullet.y > 800 || enemy_bullet.y < -5) {
enemy_bullets.splice(j,1);
}
drawEnemyBullet(enemy_bullet.x, enemy_bullet.y);
}
}
}}
This solution relies on the function Date.now() which returns the current time in milliseconds. It's possible for each enemy to keep track of when they have to fire next and each one can have a different delay between shots.
I've only added a graphic to show when they are firing their weapons, but this can be easily altered to something like a raycast or spawn a projectile particle.
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<style>
body {
background-color: black;
}
canvas {
position: absolute;
margin-left: auto;
margin-right: auto;
left: 0;
right: 0;
border: solid 1px white;
border-radius: 1px;
}
</style>
</head>
<body>
<canvas id="canvas"></canvas>
<script type="application/javascript">
// Enemy constructor
function Enemy(x,y) {
this.x = x;
this.y = y;
this.isFiring = false;
this.fireDelay = (500 + Math.random() * 500) | 0; // Time between shots
this.lastFired = Date.now(); // Last time at which the enemy fired
}
/*
Enemy prototype
(All objects created using the constructor share these properties)
E.G.
var e1 = new Enemy(10,0);
var e2 = new Enemy(20,0);
if (e1.__proto__ === e2.__proto__) {
console.log("Match");
}
prints "Match"
*/
Enemy.prototype = {
WIDTH: 10,
HEIGHT: 20,
FIRE_DURATION: 100, // Amount of time 'fire' graphic is shown
FIRE_WIDTH: 10,
FIRE_HEIGHT: 10,
update: function() {
// If current time - time when I last fired > the amount of time between shots
if (Date.now() - this.lastFired > this.fireDelay) {
this.lastFired = Date.now();
this.isFiring = true;
// If you were using projectile particles, this is where you would spawn one
}
if (this.isFiring && Date.now() - this.lastFired > this.FIRE_DURATION) {
this.isFiring = false;
}
},
render: function(ctx) {
ctx.fillStyle = "darkred";
ctx.strokeStyle = "black";
ctx.lineWidth = 2;
ctx.beginPath();
ctx.rect(
this.x,
this.y,
this.WIDTH,
this.HEIGHT
);
ctx.fill();
ctx.stroke();
if (this.isFiring) {
ctx.fillStyle = "yellow";
ctx.strokeStyle = "darkyellow";
ctx.lineWidth = 3;
ctx.beginPath();
ctx.rect(
this.x + this.WIDTH,
this.y + this.HEIGHT * 0.5 - this.FIRE_HEIGHT * 0.5,
this.FIRE_WIDTH,
this.FIRE_HEIGHT
);
ctx.fill();
ctx.stroke();
}
}
};
var canvasWidth = 180;
var canvasHeight = 160;
var canvas = null;
var ctx = null;
var enemies = [];
window.onload = function() {
canvas = document.getElementById("canvas");
canvas.width = canvasWidth;
canvas.height = canvasHeight;
ctx = canvas.getContext("2d");
for (var i = 0; i < 5; ++i) {
enemies[i] = new Enemy(20 + i * 3,10 + i * 30);
}
loop();
}
function loop() {
// Update
for (var i = 0; i < enemies.length; ++i) {
enemies[i].update();
}
// Render
ctx.fillStyle = "gray";
ctx.fillRect(0,0,canvasWidth,canvasHeight);
for (var i = 0; i < enemies.length; ++i) {
enemies[i].render(ctx);
}
//
requestAnimationFrame(loop);
}
</script>
</body>
</html>
When I try to change the scoreboard using the computerCount variable (as you can see in my if statement in the update function for the ball variable) the other numbers aren't shown properly. Keep in mind that at first 0 works properly.
JSFiddle format - You can change code by going at top right corner that says "Edit" in JSFiddle.
Code:
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Pong</title>
<!-- Basic styling, centering the canvas -->
<style>
canvas{
position: absolute;
margin: auto;
top:60px;
bottom:0;
right:0;
left:0;
}
#scoreBoard{
position: absolute;
margin: auto;
top:0;
bottom:640px;
right:720px;
left:20px;
}
</style>
</head>
<body>
<canvas id = "scoreBoard" width="500" height = "100"></canvas>
<script>
var WIDTH = 700
var HEIGHT = 600
var pi = Math.PI
var canvas
var ctx
var keystate
var upArrow = 38;
var downArrow = 40;
var computerCount = 0;
var playerCount = 0;
var player = {
x: null,
y: null,
width: 20,
height: 100,
/**
* Update the position depending on pressed keys
*/
update: function() {
if(keystate[upArrow]){
this.y-=7;
}
if(keystate[downArrow]){
this.y+=7;
}},
/**
* Draw the player paddle to the canvas
*/
draw: function() {
ctx.fillRect(this.x, this.y, this.width, this.height);
}
}
/**
* The ai paddle
*
* #type {Object}
*/
var ai = {
x: null,
y: null,
width: 20,
height: 100,
/**
* Update the position depending on the ball position
*/
update: function() {
var desty = ball.y-(this.height - ball.side)*0.5
this.y += (desty-this.y)*0.2;
},
draw: function() {
ctx.fillRect(this.x, this.y, this.width, this.height);
}
}
/**
* The ball object
*
* #type {Object}
*/
var ball = {
x: null,
y: null,
vel:null,
side: 20,
speed:5,
update: function() {
this.x += this.vel.x;
this.y += this.vel.y;
if(0>this.y || this.y+this.side>HEIGHT){
var offset = this.vel.y<0 ? 0-this.y : HEIGHT-(this.y+this.side);
this.y+=2*offset
this.vel.y*=-1;
}
var AABBIntersect = function(ax, ay, aw, ah, bx, by, bw, bh) {
return ax < bx+bw && ay < by+bh && bx < ax+aw && by < ay+ah;
};
var pdle = this.vel.x<0 ? player : ai;
if(AABBIntersect(pdle.x,pdle.y,pdle.width,pdle.height, this.x, this.y, this.side, this.side)){
this.x = pdle===player ? player.x + player.width : ai.x - this.side;
var n = (this.y+this.side-pdle.y)/(pdle.height+this.side)
var phi = 0.25*pi*(2*n - 1) // pi/4 = 45
this.x = pdle===player ? player.x+player.width : ai.x - this.side;
var n = (this.y+this.side - pdle.y)/(pdle.height+this.side);
var phi = 0.25*pi*(2*n - 1); // pi/4 = 45
this.vel.x = (pdle===player ? 1 : -1)*this.speed*Math.cos(phi);
this.vel.y = this.speed*Math.sin(phi);
}
if(ball.x<0){
computerCount =+1;
ball.x = (WIDTH - ball.side) / 2;
ball.y = (HEIGHT - ball.side) / 2;
}
},
// reset the ball when ball outside of the canvas in the
draw: function() {
ctx.fillRect(this.x, this.y, this.side, this.side);
}
}
function score(){
}
/**
* Starts the game
*/
function main() {
// create, initiate and append game canvas
canvas = document.createElement("canvas");
canvas.width = WIDTH;
canvas.height = HEIGHT;
ctx = canvas.getContext("2d");
document.body.appendChild(canvas);
canvas2 = document.createElement("canvas");
canvas2.setAttribute("id", "scoreBoard");
canvas2.width = 200;
canvas2.height = 100;
ctx2 = canvas2.getContext("2d");
document.body.appendChild(canvas2);
keystate = {};
document.addEventListener("keydown" , function(event){
keystate[event.keyCode] = true;
})
document.addEventListener("keyup" , function(event){
delete keystate[event.keyCode];
})
init();
var loop = function() {
update();
draw();
window.requestAnimationFrame(loop, canvas);
};
window.requestAnimationFrame(loop, canvas);
}
/**
* Initatite game objects and set start positions
*/
function init() {
player.x = player.width;
player.y = (HEIGHT - player.height) / 2;
ai.x = WIDTH - (player.width + ai.width);
ai.y = (HEIGHT - ai.height) / 2;
ball.x = (WIDTH - ball.side) / 2;
ball.y = (HEIGHT - ball.side) / 2;
ball.vel = {
x:ball.speed,
y: 0
}
}
/**
* Update all game objects
*/
function update() {
ball.update();
player.update();
ai.update();
}
function draw(){
ctx.fillStyle = "black"
ctx.fillRect(0,0,WIDTH,HEIGHT)
ctx.save();
ctx2.fillStyle = "red"
ctx2.fillText(String(computerCount),100,100)
ctx2.fillText("VS",120,100)
ctx2.fillText(String(playerCount),175,100)
ctx2.font = "bold 40px monaco"
ctx.fillStyle = "white"
ball.draw();
player.draw();
ai.draw();
var w=4;
var x= (WIDTH-w)*0.5;
var y=2;
var step = HEIGHT/20;
while(y<HEIGHT){
ctx.fillRect(x,y+step*0.25,w,step*0.5)
y+=step;
}
ctx.restore();
}
// start and run the game
main();
</script>
</body>
</html>
You have two problems:
When you draw a number, you do not erase the previous number that is already printed. That is, when the score becomes 1, you render 1 on top of already rendered 0. The easiest way to address it is to do fillRect and draw a black rectangle on top of the previously written score before you draw a new score.
When you fix that, you will notice that your score never goes above 1. The reason is a typo in the code that increments it, replace
computerCount =+1;
with
computerCount += 1;
Mentioned by #Ishamael, line 139's computer count needs to be changed to computerCount += 1; //After this if statement add if the player scores.
In line 221,
function draw(){
ctx.fillStyle = "black";
ctx.fillRect(0,0,WIDTH,HEIGHT);
ctx.save();
ctx2.fillStyle = "black";
ctx2.fillRect(0,0,WIDTH, 100);
ctx2.save();
ctx2.fillStyle = "red";
ctx2.font = "bold 40px monaco";
ctx2.fillText(String(computerCount),100,100);
ctx2.fillText("VS",120,100);
ctx2.fillText(String(playerCount),175,100);
ctx2.save();
ctx.fillStyle = "white";
. . .
}
remember your semicolons and set text style before writing. I also added the repaint to erase the previous scoreboard.
I want change the middle point of canvas quadratic curve which is far away from the line while dragging middle point. On dragging i want to stick with the link as now its increasing the distance of the middle point.http://jsfiddle.net/ashishbhatt/yqgak7eq/1/
http://s25.postimg.org/hegxhlgrj/123123.jpg
Please check the above reference image for the same.
Code :
(function() {
var canvas, ctx, code, point, style, drag = null, dPoint;
// define initial points
function Init(quadratic) {
point = {
p1: { x:0, y:100 },
p2: { x:200, y:100 }
};
if (quadratic) {
point.cp1 = { x: 100, y: 50 };
}
else {
point.cp1 = { x: 100, y: 100 };
point.cp2 = { x: 100, y: 100 };
}
// default styles
style = {
curve: { width: 2, color: "#333" },
cpline: { width: 1, color: "#C00" },
point: { radius: 6, width: 1, color: "#900", fill: "rgba(200,200,200,0.5)", arc1: 0, arc2: 2 * Math.PI }
}
// line style defaults
ctx.lineCap = "round";
ctx.lineJoin = "round";
// event handlers
canvas.onmousedown = DragStart;
canvas.onmousemove = Dragging;
canvas.onmouseup = canvas.onmouseout = DragEnd;
DrawCanvas();
}
// draw canvas
function DrawCanvas() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
// control lines
ctx.lineWidth = style.cpline.width;
ctx.strokeStyle = style.cpline.color;
ctx.beginPath();
//ctx.moveTo(point.p1.x, point.p1.y);
//ctx.lineTo(point.cp1.x, point.cp1.y);
if (point.cp2) {
//ctx.moveTo(point.p2.x, point.p2.y);
//ctx.lineTo(point.cp2.x, point.cp2.y);
}
else {
//ctx.lineTo(point.p2.x, point.p2.y);
}
ctx.stroke();
// curve
ctx.lineWidth = style.curve.width;
ctx.strokeStyle = style.curve.color;
ctx.beginPath();
ctx.moveTo(point.p1.x, point.p1.y);
if (point.cp2) {
//ctx.bezierCurveTo(point.cp1.x, point.cp1.y, point.cp2.x, point.cp2.y, point.p2.x, point.p2.y);
}
else {
ctx.quadraticCurveTo(point.cp1.x, point.cp1.y, point.p2.x, point.p2.y);
}
ctx.stroke();
// control points
for (var p in point) {
ctx.lineWidth = style.point.width;
ctx.strokeStyle = style.point.color;
ctx.fillStyle = style.point.fill;
ctx.beginPath();
ctx.arc(point[p].x, point[p].y, style.point.radius, style.point.arc1, style.point.arc2, true);
ctx.fill();
ctx.stroke();
}
ShowCode();
}
// show canvas code
function ShowCode() {
var myCounter = 0;
if(point.cp1.y < 100){
myCounter = point.cp1.y-100;
}else if(point.cp1.y > 100){
myCounter = point.cp1.y-100;
}
if (code) {
code.firstChild.nodeValue = myCounter
}
}
// start dragging
function DragStart(e) {
e = MousePos(e);
var dx, dy;
for (var p in point) {
//console.log(p)
//dx = point[p].x - e.x;
if(p == 'cp1'){
dy = point[p].y - e.y;
if ((dy * dy) < style.point.radius * style.point.radius) {
drag = p;
dPoint = e;
canvas.style.cursor = "move";
return;
}
}
}
}
// dragging
function Dragging(e) {
if (drag) {
e = MousePos(e);
//point[drag].x += e.x - dPoint.x;
point[drag].y += e.y - dPoint.y;
dPoint = e;
DrawCanvas();
}
}
// end dragging
function DragEnd(e) {
drag = null;
canvas.style.cursor = "default";
DrawCanvas();
}
// event parser
function MousePos(event) {
event = (event ? event : window.event);
return {
//x: event.pageX - canvas.offsetLeft,
y: event.pageY - canvas.offsetTop
}
}
// start
canvas = document.getElementById("canvasSettings");
code = document.getElementById("code");
if (canvas.getContext) {
ctx = canvas.getContext("2d");
Init(canvas.className == "quadratic");
}
})();