It's my first question here. I just learn canvas in JavaScript and I found a problem while adding the speed. I want to stop the rectangle if its x exceeds the width of the canvas. I am just a beginner, so please help me.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
#canvas{
border: 1px solid black;
}
</style>
</head>
<body>
<canvas id="canvas" width="400" height="400">Your browser doesn't support canvas</canvas>
<script>
var canvas = document.getElementById('canvas');
var cnxt = canvas.getContext('2d');
x = 0;
y = 50;
var t;
function draw(){
cnxt.clearRect(0,0,400,400);
cnxt.beginPath();
cnxt.rect(x,y,25,25);
cnxt.fillStyle = 'red';
cnxt.fill();
var timePassed = (performance.now()-t)/1000;
var fps = Math.round(1/ timePassed);
let speed = 100;
cnxt.font = '25px Arial';
cnxt.fillStyle = 'black';
cnxt.fillText("FPS: " + fps, 20,30);
t = performance.now();
x += (speed * timePassed);
if (x >= 400 - 25){
speed = 0;
}
window.requestAnimationFrame(draw);
}
draw();
</script>
</body>
</html>
Related
I want to add 10 to the position of the ball, but it adds position to the duplicated shape. I tried to make a separate function but it did not work.
HTML5 Code:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<canvas id="Game" width="800" height="600" style="border: 1px solid #d3d3d3;
background-color: #f1f1f1;"></canvas>
<script src="Game.js"></script>
</body>
</html>
Javascript Code:
var GameCanvas = GameCanvas = document.getElementById("Game");
var GameCtx = GameCtx = GameCanvas.getContext("2d");;
var BallSprite = 50;
window.onload = function () {
setInterval(HoldSprites, 100);
}
function HoldSprites() {
BallSprite = BallSprite + 10;
GameCtx.beginPath();
GameCtx.arc(BallSprite, 50, 40, 0, 2 * Math.PI);
GameCtx.stroke();
}
I have been trying to develop a drawing application. When I try to plot a point for freehand drawing, the point appears a good 100 or so pixels away from the actual position of the mouse pointer. Is there any way I can get the exact position of the mouse? You can see and run the code below.
const canvasEle = document.getElementById('drawContainer');
const context = canvasEle.getContext('2d');
function setMousePosition (e) {
var x = e.clientX;
var y = e.clientY;
console.log("x coord " + x + " y coord " + y);
changePixelColor(x, y)
}
function changePixelColor (x, y) {
context.fillRect(x,y,1,1);
}
canvasEle.addEventListener("mousemove", setMousePosition)
canvas {
border: 1px solid black;
width: 500px;
height: 500px;
position: absolute;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Draw</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<canvas id="drawContainer"></canvas>
</body>
<script src="app.js"></script>
</html>
Try like this:
const canvasEle = document.getElementById('drawContainer');
const context = canvasEle.getContext('2d');
const cr = canvasEle.getBoundingClientRect();
function setMousePosition (e) {
var x = e.clientX - cr.x;
var y = e.clientY - cr.y;
console.log("x coord " + x + " y coord " + y);
changePixelColor(x, y)
}
function changePixelColor (x, y) {
context.fillRect(x,y,1,1);
}
canvasEle.width = 500;
canvasEle.height = 500;
canvasEle.addEventListener("mousemove", setMousePosition)
canvas {
border: 1px solid black;
width: 500px;
height: 500px;
position: absolute;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Draw</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<canvas id="drawContainer"></canvas>
</body>
<script src="app.js"></script>
</html>
Two additions to resolve this:
offsetting the x and y values in setMousePosition, so that they become relative to the canvas position, rather than to the page.
setting the width and height of the canvas element in either JavaScript or the HTML attributes.
Try removing height and width from CSS and use the canvas' width and height attributes instead. Another tip to center the mouse on the painted rectangle is to subtract half the size of the rectangle, e.g. context.fillRect(x-0.5,y-0.5,1,1). In your case it's hard to actually see that the dot isn't centered so try with context.fillRect(x-25,y-25,50,50) and you will see a difference compared to context.fillRect(x-25,y,50,50)
const canvasEle = document.getElementById('drawContainer');
const context = canvasEle.getContext('2d');
function setMousePosition (e) {
var x = e.clientX;
var y = e.clientY;
//console.log("x coord " + x + " y coord " + y);
changePixelColor(x, y)
}
function changePixelColor (x, y) {
context.fillRect(x-0.5,y-0.5,1,1);
//context.fillRect(x,y,50,50); compare these to see the difference
//context.fillRect(x-25,y-25,50,50);
}
canvasEle.addEventListener("mousemove", setMousePosition)
canvas {
border: 1px solid black;
position: absolute;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Draw</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<canvas width="500" height="500" id="drawContainer"></canvas>
</body>
<script src="app.js"></script>
</html>
Sublime text preview in browser doesn't show the javascript that is in html. when I want to check and see it in chrome browser, it shows the html and css but doesn't do anything with js file. The code is very simple and it works (example in JSBin). (Html and js file in the same directory.)
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Practice the Basics - Two overlapping squares sample solution</title>
</head>
<body>
<canvas id="myCanvas" width="450" height="300" style="border: 1px solid black"></canvas>
<script src="rajzos.js"></script>
</body>
</html>
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
var canvasWidth = canvas.width;
var canvasHeight = canvas.height;
var size = 100;
var positionX = canvasWidth / 2 - size * 0.75;
var positionY = canvasHeight / 2 - size * 0.75;
context.fillStyle = 'rgba(255,0,0,.5)';
context.fillRect(positionX, positionY, size, size);
positionX += size / 2;
positionY += size / 2;
I don't know what should be the expected output but the script tag should be in the head of your html.
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
var canvasWidth = canvas.width;
var canvasHeight = canvas.height;
var size = 100;
var positionX = canvasWidth / 2 - size * 0.75;
var positionY = canvasHeight / 2 - size * 0.75;
context.fillStyle = 'rgba(255,0,0,.5)';
context.fillRect(positionX, positionY, size, size);
positionX += size / 2;
positionY += size / 2;
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Practice the Basics - Two overlapping squares sample solution</title>
<script src="rajzos.js"></script>
</head>
<body>
<canvas id="myCanvas" width="450" height="300" style="border: 1px solid black"></canvas>
</body>
</html>
I am trying to get the following single HTML5 page with embedded Javascript to draw a fraction of a circle dependent upon the numerator and dominator chosen.
The code was suggested by #Vanojx1 but, my post was closed because it was not 'specific' enough, and, I just want some help understanding what I am doing wrong please:
<!DOCTYPE html>
<html lang="">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="author" content="">
<meta name="description" content="Fraction Learning app for Children">
<script type="text/javascript">
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
var pi = Math.PI;
document.getElementById("draw").addEventListener("click", function () {
var num = document.getElementById("num").value;
var den = document.getElementById("den").value;
var rad = 2 / den * num * pi;
var cx = 250;
var cy = 250;
ctx.clearRect(0, 0, 500, 500);
ctx.beginPath();
ctx.moveTo(cx, cy);
ctx.arc(cx, cy, 220, 1.5 * pi, 1.5 * pi + rad);
ctx.lineTo(cx, cy);
ctx.fillStyle = "#FF0000";
ctx.fill();
ctx.closePath();
ctx.stroke();
});
</script>
<title>Fractions Fun</title>
</head>
<body>
<canvas id="myCanvas" width="500" height="500" style="border:1px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.</canvas>
<br>
<input type="number" id="num" /> /
<input type="number" id="den" />
<br>
<button id="draw">
DRAW
</button>
</body>
</html>
HTML is rendered in the order that it appears in the DOM (that includes script blocks). Therefore the script block will be run before draw is rendered. As draw does not exist the script fails to add the click handler.
Putting the code in a function and call it using the body's onload event would allow the click handler to be added. See below -
<!DOCTYPE html>
<html lang="">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="author" content="">
<meta name="description" content="Fraction Learning app for Children">
<script type="text/javascript">
function init() {
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
var pi = Math.PI;
document.getElementById("draw").addEventListener("click", function() {
var num = document.getElementById("num").value;
var den = document.getElementById("den").value;
var rad = 2 / den * num * pi;
var cx = 250;
var cy = 250;
ctx.clearRect(0, 0, 500, 500);
ctx.beginPath();
ctx.moveTo(cx, cy);
ctx.arc(cx, cy, 220, 1.5 * pi, 1.5 * pi + rad);
ctx.lineTo(cx, cy);
ctx.fillStyle = "#FF0000";
ctx.fill();
ctx.closePath();
ctx.stroke();
});
}
</script>
<title>Fractions Fun</title>
</head>
<body onload="init()">
<canvas id="myCanvas" width="500" height="500" style="border:1px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.</canvas>
<br>
<input type="number" id="num" />/
<input type="number" id="den" />
<br>
<button id="draw">
DRAW
</button>
</body>
Another method I've seen used is to put the script tag at the end of the document (although I'm not sure if it's considered best practice and I don't use it myself) -
<!DOCTYPE html>
<html lang="">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="author" content="">
<meta name="description" content="Fraction Learning app for Children">
<title>Fractions Fun</title>
</head>
<body>
<canvas id="myCanvas" width="500" height="500" style="border:1px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.</canvas>
<br>
<input type="number" id="num" />/
<input type="number" id="den" />
<br>
<button id="draw">
DRAW
</button>
<script type="text/javascript">
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
var pi = Math.PI;
document.getElementById("draw").addEventListener("click", function() {
var num = document.getElementById("num").value;
var den = document.getElementById("den").value;
var rad = 2 / den * num * pi;
var cx = 250;
var cy = 250;
ctx.clearRect(0, 0, 500, 500);
ctx.beginPath();
ctx.moveTo(cx, cy);
ctx.arc(cx, cy, 220, 1.5 * pi, 1.5 * pi + rad);
ctx.lineTo(cx, cy);
ctx.fillStyle = "#FF0000";
ctx.fill();
ctx.closePath();
ctx.stroke();
});
</script>
</body>
So I'm trying to work on a Canvas demo, and I want this square to move from one side to the other, but I can't figure out how to call JavaScript in a way that repeats every 60 seconds.
Here's what I got so far:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Canvas test</title>
<meta charset="utf-8" />
<link href="/bms/style.css" rel="stylesheet" />
<style>
body { text-align: center; background-color: #000000;}
canvas{ background-color: #ffffff;}
</style>
<script type="text/javascript">
var x = 50;
var y = 250;
function update(){
draw();
x = x + 5;
}
function draw(){
var canvas = document.getElementById('screen1');
if (canvas.getContext){
var ctx = canvas.getContext('2d');
ctx.fillStyle = 'rgb(236,138,68)';
ctx.fillRect(x,y,24,24);
}
}
</script>
</head>
<body onLoad="setTimeout(update(), 0);">
<canvas id="screen1" width="500" height="500"></canvas>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<title>Canvas test</title>
<meta charset="utf-8" />
<link href="/bms/style.css" rel="stylesheet" />
<style>
body { text-align: center; background-color: #000000;}
canvas{ background-color: #ffffff;}
</style>
</head>
<body>
<canvas id="screen1" width="500" height="500"></canvas>
<script type="text/javascript">
var x = 50;
var y = 250;
function update(){
draw();
x = x + 5;
}
function draw(){
var canvas = document.getElementById('screen1');
if (canvas.getContext){
var ctx = canvas.getContext('2d');
ctx.fillStyle = 'rgb(236,138,68)';
ctx.fillRect(x,y,24,24);
}
}
update();
setInterval ( update, 60000 );
</script>
</body>
</html>
1000ms = 1 second, 60000 = 60 seconds.
Using setTimeout, instead of setInterval, allows you to stop the animation with clearTimeout and the use of a variable.
(edit: this whole thing doesn't work in IE, but the setTimeout - clearTimeout combo itself should... also changed the onload and onclick events)
<!DOCTYPE html>
<html lang="en">
<head>
<title>Canvas test</title>
<meta charset="utf-8" />
<link href="/bms/style.css" rel="stylesheet" />
<style>
body { text-align: center; background-color: #000000;}
canvas{ background-color: #ffffff;}
</style>
<script type="text/javascript">
var x = 50;
var y = 250;
function update()
{
draw();
x = x + 5;
// For one minute, you would use 60000 instead of 100.
// 100 is so you can actually see it move.
myToggle = setTimeout(update, 100);
};
function draw()
{
var canvas = document.getElementById('screen1');
if (canvas.getContext)
{
var ctx = canvas.getContext('2d');
ctx.fillStyle = 'rgb(236,138,68)';
ctx.fillRect(x,y,24,24);
}
};
function stop()
{
clearTimeout(myToggle);
};
window.onload = function()
{
document.getElementById("stop").onclick = function() { stop(); };
document.getElementById("start").onclick = function() { update(); };
update();
};
</script>
</head>
<body>
<canvas id="screen1" width="500" height="500"></canvas><br/>
<input id="stop" type="button" value="Stop" /><br/>
<input id="start" type="button" value="Start" />
</body>
</html>