Hi I looked for hours on this site and on internet in general how to move an object with html5/javascript and I founded a lot of answers but none of that answers was for me useful. I want to explain my problem: I just want to make move one of this two rectangles with the keyboard control but it's too difficult to me without help (I'm just 2 month learning javascript/css/html5).
Please do not give a bad vote to that question, I want to help and to be helped on this site.
This is the code:
<!DOCTYPE html>
<html>
<body>
<canvas id="myCanvas" width="400" height="300" style="border:1px solid #c3c3c3;">
Your browser does not support the canvas element.
</canvas>
<script>
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
ctx.fillStyle = "#FF0000";
ctx.fillRect(0,0,30,30);
var canvas1 = document.getElementById("myCanvas1");
var ctx = canvas.getContext("2d");
ctx.fillStyle = "#FF0000";
ctx.fillRect(150,150,30,30);
</script>
</body>
</html>
Thanks guys, I want to learn here from Italy but there aren't the right schools/courses and I have to work hard on the internet to do that.
You need to listen to the keyboard events, and capture the keycodes of the keys with which you want to move the rectangle. You can then increment/decrement the absolute position of your rectangle object to move it.
document.addEventListener('keydown', function(event) {
if(event.keyCode == 37) {
object.x -= 1;
}
//top
else if(event.keyCode == 38) {
object.y -= 1;
}
//right
else if(event.keyCode == 39) {
object.x += 1;
}
//bottom
else if(event.keyCode == 40) {
object.y += 1;
}
}
Here is a working example
#Simone P: Inside your script, try this:
var ctx = canvas.getContext("2d");
function clean() {
canvas.width = canvas.width;
}
var positionDef = { x: 30, y: 30 };
var position = { x: 30, y: 30 };
ctx.fillStyle="#FF0000";
ctx.fillRect(position.x,position.y,20,20);
var move = {
up: function() {
clean();
ctx.fillStyle="#FF0000";
position.y -= 3;
ctx.fillRect(position.x,position.y,20,20);
},
right: function() {
clean();
ctx.fillStyle="#FF0000";
position.x += 3;
ctx.fillRect(position.x,position.y,20,20);
},
down: function() {
clean();
ctx.fillStyle="#FF0000";
position.y += 3;
ctx.fillRect(position.x,position.y,20,20);
},
left: function() {
clean();
ctx.fillStyle="#FF0000";
position.x -= 3;
ctx.fillRect(position.x,position.y,20,20);
},
}
function keyDownEvent(e) {
switch(e.keyCode) {
case 40:
move.down();
break;
case 39:
move.right();
break;
case 38:
move.up();
break;
case 37:
move.left();
break;
}
}
document.addEventListener("keydown", keyDownEvent, false);
I tried with that code but I think I'm using that bad:
<!DOCTYPE html>
<html>
<body>
<canvas id="myCanvas" width="400" height="300"
style="border:1px solid #c3c3c3;">
Your browser does not support the canvas element.
</canvas>
<script>
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
ctx.fillStyle = "#FF0000";
ctx.fillRect(0,0,30,30);
var canvas = document.getElementById("myCanvas");
var ctx1 = canvas.getContext("2d");
ctx.fillStyle = "#FF0000";
ctx.fillRect(150,150,30,30);
}
document.addEventListener('keydown', function(event) {
if(event.keyCode == 37) {
ctx1.x -= 1;
}
//top
else if(event.keyCode == 38) {
ctx1.y -= 1;
}
//right
else if(event.keyCode == 39) {
ctx1.x += 1;
}
//bottom
else if(event.keyCode == 40) {
ctx1.y += 1;
}
}
</script>
</body>
</html>
I Think you forget to draw the canvas. Ctx.x and so on just set the position but not draw. So maybe you have to call dr w() function
To yRand
Where I should add the draw function? Can you please insert that by yourself into the code? :o
<!DOCTYPE html>
<html>
<body>
<canvas id="myCanvas" width="400" height="300"
style="border:1px solid #c3c3c3;">
Your browser does not support the canvas element.
</canvas>
<script>
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
ctx.fillStyle = "#FF0000";
ctx.fillRect(0,0,30,30);
var canvas = document.getElementById("myCanvas");
var ctx1 = canvas.getContext("2d");
ctx.fillStyle = "#FF0000";
ctx.fillRect(150,150,30,30);
}
document.addEventListener('keydown', function(event) {
if(event.keyCode == 37) {
ctx1.x -= 1;
}
//top
else if(event.keyCode == 38) {
ctx1.y -= 1;
}
//right
else if(event.keyCode == 39) {
ctx1.x += 1;
}
//bottom
else if(event.keyCode == 40) {
ctx1.y += 1;
}
}
</script>
</body>
</html>
#yRand Thanks!!!!!
It works :)
<!DOCTYPE html>
<html>
<body>
<canvas id="myCanvas" width="400" height="300" style="border:1px solid #c3c3c3;">
Your browser does not support the canvas element.
</canvas>
<script>
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
ctx.fillStyle = "#FF0000";
ctx.fillRect(0,0,30,30);
var canvas1 = document.getElementById("myCanvas1");
var ctx = canvas.getContext("2d");
ctx.fillStyle = "#FF0000";
ctx.fillRect(150,150,30,30);
var ctx = canvas.getContext("2d");
function clean() {
canvas.width = canvas.width;
}
var positionDef = { x: 30, y: 30 };
var position = { x: 30, y: 30 };
ctx.fillStyle="#FF0000";
ctx.fillRect(position.x,position.y,20,20);
var move = {
up: function() {
clean();
ctx.fillStyle="#FF0000";
position.y -= 3;
ctx.fillRect(position.x,position.y,20,20);
},
right: function() {
clean();
ctx.fillStyle="#FF0000";
position.x += 3;
ctx.fillRect(position.x,position.y,20,20);
},
down: function() {
clean();
ctx.fillStyle="#FF0000";
position.y += 3;
ctx.fillRect(position.x,position.y,20,20);
},
left: function() {
clean();
ctx.fillStyle="#FF0000";
position.x -= 3;
ctx.fillRect(position.x,position.y,20,20);
},
}
function keyDownEvent(e) {
switch(e.keyCode) {
case 40:
move.down();
break;
case 39:
move.right();
break;
case 38:
move.up();
break;
case 37:
move.left();
break;
}
}
document.addEventListener("keydown", keyDownEvent, false);
</script>
</body>
</html>
The other rectangles when i press the keys desappear... how to fix them?
Related
The aim is to able to write using mouse movement on video on pause.
I am using an HTML5 Video tag to play video.
I am able to play the video without any issue, apart from playing video I need to write able to draw on video on the pause of the video
I am able to write on canvas. But when I have a video tag in canvas, I am NOT able to view any of my drawings.
Can you please let me know, what I am doing wrong?
Below is the code:
<html>
<!-- <body onload="init()"> -->
<body>
<canvas id="can" width="400" height="400" style="position:absolute;top:10%;left:10%;border:2px solid;">
</canvas>
<video id="can" width="400" height="400" style="position:absolute;top:10%;left:10%;border:2px solid;">
<source src="Test.mp4" type="video/mp4">
</video>
</body>
<script type="text/javascript">
var canvas, ctx, flag = false,
prevX = 0,
currX = 0,
prevY = 0,
currY = 0,
dot_flag = false;
var x = "black",
y = 2;
//# must await page load via JS (before using JS functions)...
addEventListener("load", init );
function init()
{
canvas = document.getElementById('can');
ctx = canvas.getContext("2d");
w = canvas.width;
h = canvas.height;
canvas.addEventListener("mousemove", function (e) { findxy('move', e)}, false);
canvas.addEventListener("mousedown", function (e) { findxy('down', e) }, false);
canvas.addEventListener("mouseup", function (e) { findxy('up', e)}, false);
canvas.addEventListener("mouseout", function (e) { findxy('out', e)}, false);
}
function draw()
{
ctx.beginPath();
ctx.moveTo(prevX, prevY);
ctx.lineTo(currX, currY);
ctx.strokeStyle = x;
ctx.lineWidth = y;
ctx.stroke();
ctx.closePath();
}
function erase()
{
var m = confirm("Want to clear");
if (m)
{
ctx.clearRect(0, 0, w, h);
document.getElementById("canvasimg").style.display = "none";
}
}
function save()
{
document.getElementById("canvasimg").style.border = "2px solid";
//var dataURL = canvas.toDataURL();
//document.getElementById("canvasimg").src = dataURL;
document.getElementById("canvasimg").src = canvas.toDataURL();
document.getElementById("canvasimg").style.display = "inline";
}
function findxy(res, e)
{
if (res == 'down')
{
prevX = currX;
prevY = currY;
currX = e.clientX - canvas.offsetLeft;
currY = e.clientY - canvas.offsetTop;
flag = true;
dot_flag = true;
if (dot_flag)
{
ctx.beginPath();
ctx.fillStyle = x;
ctx.fillRect(currX, currY, 2, 2);
ctx.closePath();
dot_flag = false;
}
}
if (res == 'up' || res == "out")
{ flag = false; }
if (res == 'move')
{
if (flag)
{
prevX = currX;
prevY = currY;
currX = e.clientX - canvas.offsetLeft;
currY = e.clientY - canvas.offsetTop;
draw();
}
}
}
function color(obj)
{
switch (obj.id)
{
case "green": x = "green"; break;
case "blue": x = "blue"; break;
case "red": x = "red"; break;
case "yellow": x = "yellow"; break;
case "orange": x = "orange"; break;
case "black":
x = "black";
break;
case "white":
x = "white";
break;
}
if (x == "white") y = 14;
else y = 2;
}
</script>
</html>
I am trying to make the image switch when I press the space bar. but.... when I do I get an error "ig is not defined" Im not sure why its happening any ideas? I should also note that I am using notepad its the free text editor on windows 10 im sure the same code works on mac and linux
Here is the code:
<!DOCTYPE html>
<html>
<canvas id="gameCanvas" width="800" height="600"></canvas>
<script>
var canvas
var ctx
window.onload = function() {
canvas = document.getElementById("gameCanvas")
ctx = canvas.getContext("2d")
ctx.fillStyle = "red"
ctx.fillRect(0, 0, 50, 50)
}
function draw() {
ctx.clearRect(0, 0, 999, 999)
Xpos = Xpos + Xspeed
ctx.fillRect(Xpos, 0, 20, 20)
var ig = new Image()
ig.src = "alien2.png"
var img = new Image();
img.src = "scp.png";
ctx.drawImage(img, Xpos, 145, 50, 50);
}
document.addEventListener("keydown", keyDown)
document.addEventListener("keyup", keyUp)
var Xspeed = 0
var Xpos = 10
setInterval(draw, 50)
function keyUp(evt) {
if (evt.keyCode == 32) Xspeed = 0
ctx.drawImage(ig, 100, 100)
}
function keyDown(evt) {
if (evt.keyCode == 32) Xspeed = 2
ctx.drawImage(ig, 100, 100)
}
</script>
</html>
Move the functions inside the onload event listener so the functions can reference ctx and make ig a global variable:
var canvas
var ctx
window.onload = function() {
canvas = document.getElementById("gameCanvas")
ctx = canvas.getContext("2d")
ctx.fillStyle = "red"
ctx.fillRect(0, 0, 50, 50)
function draw() {
ctx.clearRect(0, 0, 999, 999)
Xpos = Xpos + Xspeed
ctx.fillRect(Xpos, 0, 20, 20)
window.ig = new Image()
ig.src = "https://www.gravatar.com/avatar/0fdacb141bca7fa57c392b5f03872176?s=48&d=identicon&r=PG&f=1";
var img = new Image();
img.src = "https://www.gravatar.com/avatar/0fdacb141bca7fa57c392b5f03872176?s=48&d=identicon&r=PG&f=1";
ctx.drawImage(img, Xpos, 145, 50, 50);
}
document.addEventListener("keydown", keyDown)
document.addEventListener("keyup", keyUp)
var Xspeed = 0
var Xpos = 10
setInterval(draw, 50)
function keyUp(evt) {
if (evt.keyCode == 32) Xspeed = 0
ctx.drawImage(ig, 100, 100)
}
function keyDown(evt) {
if (evt.keyCode == 32) Xspeed = 2
ctx.drawImage(ig, 100, 100)
}
}
<!DOCTYPE html>
<html>
<body>
<canvas id="gameCanvas" width="800" height="600"></canvas>
</body>
</html>
I have been looking for a while on how to move a certain square around on a canvas with JavaScript, and haven't found much. I have done one where it removes itself and replaces itself every frame, but I want it to be smoother and animated. This is my code:
<canvas id="myCanvas" width="200" height="100" style="border:1px solid grey;"></canvas><br />
<button onclick="#">Move Up</button>
<script>
canvas = document.getElementById("myCanvas");
ctx = canvas.getContext("2d");
ctx.fillStyle = "#FF0000";
ctx.fillRect(20, 60, 20, 20);
</script>
So far the button does nothing, is there a function I could add that would move the square around? (in this case up)
To make smooth animations, check about the requestAnimationFrame function (https://developer.mozilla.org/fr/docs/Web/API/Window/requestAnimationFrame).
Here an example with your code:
canvas = document.getElementById('myCanvas');
ctx = canvas.getContext('2d');
var squareY = 60;
var isButtonPressed = false;
ctx.fillStyle = '#FF0000';
ctx.fillRect(20, squareY, 20, 20);
function moveUp() {
window.requestAnimationFrame(moveUp);
if (isButtonPressed) {
squareY -= 10 / 16;
}
squareY = Math.max(squareY, 5);
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = '#FF0000';
ctx.fillRect(20, squareY, 20, 20);
}
function onMouseUp() {
isButtonPressed = false;
}
function onMouseDown() {
isButtonPressed = true;
}
canvas = document.getElementById('myCanvas');
ctx = canvas.getContext('2d');
var squareY = 60;
var isButtonPressed = false;
ctx.fillStyle = '#FF0000';
ctx.fillRect(20, squareY, 20, 20);
function moveUp() {
window.requestAnimationFrame(moveUp);
if (isButtonPressed) {
squareY -= 10 / 16;
}
squareY = Math.max(squareY, 5);
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = '#FF0000';
ctx.fillRect(20, squareY, 20, 20);
}
function onMouseUp() {
isButtonPressed = false;
}
function onMouseDown() {
isButtonPressed = true;
}
window.addEventListener('keydown', function (e) {
if (e.key == 'ArrowUp') {
// if the arrow key is pressed
squareY -= 10 / 16;
}
});
moveUp();
<canvas id="myCanvas" width="200" height="100" style="border:1px solid grey;"></canvas><br />
<button onmousedown="onMouseDown()" onmouseup="onMouseUp()">Move Up</button>
<script>
</script>
Someone please can help me with an object moving automatically when I click on the right arrow in canvas.
My code is
if(e.keyCode == 39) {
bullet.x = +5;
setTimeout(function() {
ctx.clearRect(0,0,canvas.width,canvas.height)
ctx.drawImage(player.Image, player.x, player.y , player.width, player.height);
ctx.drawImage(bullet.Image , bullet.x , bullet.y , bullet.width , bullet.height);
}, 300);
console.log("DOWN");
}
What do I need to add for the object moving by the right arrow?
It is necessary to use ClearReact to advance with the function setInterval ()
let canvas = document.getElementById("mycanvas");
let ctx = canvas.getContext('2d');
juego();
let ev;
let x = 0;
let base_image = new Image();
base_image.src = 'https://img.icons8.com/pastel-glyph/2x/search.png';
window.onkeydown = function(e) {
this.ev = e;
}
function draw() {
if (typeof this.ev != 'undefined' && this.ev.keyCode == 39) {
x = x + 10;
ctx.clearRect(0, 0, canvas.width, canvas.height)
ctx.drawImage(base_image, x, 10);
}
}
function juego() {
pat = ctx.createPattern(canvas, "repeat");
window.setInterval(draw, 500);
}
canvas {
outline: black 3px solid;
}
<canvas id="mycanvas" width="150" height="150"></canvas>
for try press left arrow
I have a Javascript program working in three different places: here,
here, and here.
But I don't know how would I put them in one file. This is where I am at right now.
<!DOCTYPE html>
<html>
<head>
<title>TEST</title>
<style>
body {
background-color:#E4E0FF;
}
#canvas {
border:10px solid red;
background-color:white;
}
#canvas2 {
border:10px solid red;
background-color:white;
}
#canvas3 {
border:10px solid red;
background-color:white;
}
</style>
</head>
<body>
<canvas id="canvas" width="400" height="300">
</canvas>
<canvas id="canvas2" width="400" height="300">
</canvas>
<canvas id="canvas3" width="400" height="300">
</canvas>
<script src="http://code.jquery.com/jquery-latest.min.js"
type="text/javascript"></script>
<script type="text/javascript">
var c = document.getElementById("canvas");
var ctx = c.getContext("2d");
var $canvas = $("#canvas");
var canvasOffset = $canvas.offset();
var offsetX = canvasOffset.left;
var offsetY = canvasOffset.top;
var scrollX = $canvas.scrollLeft();
var scrollY = $canvas.scrollTop();
var toggle=0;
var x=150;
var y=100;
var w=100;
var h=100;
var r=60;
var wasInside=false;
ctx.fillStyle = "#000000";
ctx.fillRect(x, y, w, h);
function changeColor() {
if (toggle == 0) {
ctx.fillStyle = "#04B45F";
toggle = 1;
} else if (toggle ==1){
ctx.fillStyle = "#04B45F";
toggle = 2;
}else if (toggle == 2){
ctx.fillStyle = "#0000FF";
toggle = 3;
}else if (toggle == 3){
ctx.fillStyle == "#190707";
toggle = 4;
}else if (toggle == 4){
ctx.fillStyle = "#210B61";
toggle = 5;
}else if (toggle == 5){
ctx.fillStyle = "#FA58AC";
toggle = 6;
}else if (toggle ==6){
ctx.fillStyle = "#FFFF00";
toggle = 7;
}else{
ctx.fillStyle = "#F5A9D0";
toggle = 0;
}
ctx.fillRect(x, y, w, h);
}
function changeRadius() {
ctx.fillStyle = "#FFFFFF";
ctx.fillRect(0,0, 400, 300);
r = Math.floor((Math.random() * 80) + 20);
ctx.beginPath();
ctx.arc(200, 150, r, 0, 2 * Math.PI);
ctx.stroke();
}
function changeWidth() {
ctx.fillStyle = "#FFFFFF";
ctx.fillRect(0,0, 400, 300);
width = Math.floor((Math.random()*50)+1);
ctx.lineWidth=width;
ctx.stroke();
}
function handleMouseMove(e) {
var mx = parseInt(e.clientX - offsetX);
var my = parseInt(e.clientY - offsetY);
var isInsideNow = (mx > x && mx < x + w && my > y && my <= y + h);
if (isInsideNow && !wasInside) {
changeColor();
wasInside = true;
} else if (!isInsideNow && wasInside) {
wasInside = false;
}
}
$("#canvas").mousemove(function (e) {
handleMouseMove(e);
});
$("#canvas2").mousemove(function (e) {
handleMouseMove(e);
});
$("#canvas3").mousemove(function (e) {
handleMouseMove(e);
});
</script>
</body>
</html>
So, how would I tell the program to do circle thing in 2nd canvas and line in 3rd canvas???
I haven't called the changeWidth and changeRadius functions yet, because it'll just do it in the first canvas making a mess.
I just need something in this part of the code to call different functions in different canvas's
if (isInsideNow && !wasInside) {
changeColor();
wasInside = true;
} else if (!isInsideNow && wasInside) {
wasInside = false;
}
I'm not a canvas expert, but just for giving you an idea, check this FIDDLE
var c = document.getElementById("canvas");
var ctx = c.getContext("2d");
inspect these 2 lines, the context ctx wil draw in the canvas with id=canvas. you can create other contex variables to draw in the other canvas or reuse the same.
updated FIDDLE
Update for the update: FIDDLE