The aim is to be able to draw a line starting with mousedown and finishing with mouseup. In between, the line is drawn onto the canvas with the draw() function while mousemouse. I need to clear the canvas while the line is dragged.
JS:
var c = document.getElementById("canvas1");
var ctx = c.getContext("2d");
var isDrawing = false;
var mX, mY, rX, rY;
function InitThis() {
c.onmousedown = function(e) {
isDrawing = true;
mX = e.clientX;
mY = e.clientY;
};
c.onmousemove = function(e) {
if (isDrawing) {
rX = e.clientX;
rY = e.clientY;
draw();
ctx.clearRect(0, 0, canvas.width, canvas.height);
}
};
c.onmouseup = function(e) {
rX = e.clientX;
rY = e.clientY;
isDrawing = false;
}
}
function draw() {
ctx.beginPath();
ctx.moveTo(mX,mY);
ctx.lineTo(rX, rY);
ctx.closePath();
ctx.stroke();
}
InitThis()
HTML:
<!DOCTYPE html>
<html>
<head>
<meta name="description" content="[draw lines with mouse]">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<canvas id="canvas1" width="800" height="900" style="border:1px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.</canvas>
</body>
</html>
I get this error:
ReferenceError: canvas is not defined
at HTMLCanvasElement.InitThis.c.onmousemove (zivuqeyure.js:22:31)
How can I reference the canvas inside the function?
You are referencing a canvas object with the variable “c”.
This is the first line of code.
Later, you try to refer to the “canvas” variable, which is not defined. (You should use “c” instead of “canvas”)
The interpreter doesn’t know that by “canvas” you mean “the canvas object, which is stored in c”.
The interpreter does exactly what you tell it, but you tried to refer to a variable that doesn’t exist.
Related
i want to let my users to draw their signatures to approve that they accept my user agreements. I created canvas and javascript code, but instead of drawing under the mouse, it draws next to it.
You can see how it works here:
https://streamable.com/lz9h1z
JS CODE:
// Select the canvas element
const canvas = document.getElementById('signature-pad');
const ctx = canvas.getContext('2d');
// Set up event listeners
let isDrawing = false;
let lastX = 0;
let lastY = 0;
canvas.addEventListener('mousedown', e => {
isDrawing = true;
lastX = e.offsetX;
lastY = e.offsetY;
});
canvas.addEventListener('mousemove', e => {
if (isDrawing) {
ctx.beginPath();
ctx.moveTo(lastX, lastY);
ctx.lineTo(e.offsetX, e.offsetY);
ctx.stroke();
lastX = e.offsetX;
lastY = e.offsetY;
}
});
canvas.addEventListener('mouseup', () => {
isDrawing = false;
});
canvas.addEventListener('mouseout', () => {
isDrawing = false;
});
// Set up button event listeners
const clearButton = document.getElementById('clear-button');
clearButton.addEventListener('click', () => {
ctx.clearRect(0, 0, canvas.width, canvas.height);
});
const saveButton = document.getElementById('save-button');
saveButton.addEventListener('click', () => {
const dataURL = canvas.toDataURL();
console.log(dataURL);
});
HTML CODE:
<canvas id="signature-pad" width="400" height="200"></canvas>
I was trying to do something with offsets but still no idea.
You can get the mouse position using this code
function getMouse(e) {
var rect = canvas.getBoundingClientRect();
mouseX = (e.clientX - rect.left) / (rect.right - rect.left) * canvas.width,
mouseY = (e.clientY - rect.top) / (rect.bottom - rect.top) * canvas.height;
}
Check out the replit here: https://VeneratedJovialCryptos.hackinggo306.repl.co
I have create an html file with the JS that is related just to the canvas, and everything works as expected. Here is the code:
<!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>
</head>
<body>
<canvas id="signature-pad" width="400" height="200"></canvas>
<script>
// Select the canvas element
const canvas = document.getElementById('signature-pad');
const ctx = canvas.getContext('2d');
// Set up event listeners
let isDrawing = false;
let lastX = 0;
let lastY = 0;
canvas.addEventListener('mousedown', e => {
isDrawing = true;
lastX = e.offsetX;
lastY = e.offsetY;
});
canvas.addEventListener('mousemove', e => {
if (isDrawing) {
ctx.beginPath();
ctx.moveTo(lastX, lastY);
ctx.lineTo(e.offsetX, e.offsetY);
ctx.stroke();
lastX = e.offsetX;
lastY = e.offsetY;
}
});
canvas.addEventListener('mouseup', () => {
isDrawing = false;
});
canvas.addEventListener('mouseout', () => {
isDrawing = false;
});
</script>
</body>
</html>
Here is the result of running this html file: https://streamable.com/69bwa9
So you can try to place this code in a separate file, and see if everything works- if yes, then you should look for a problem in other parts of the code, if still no, maybe if is something about differences between physical machines, I am trying this on Mac.
I have an HTML page that allows a person to draw. Its very simple. The code for It is included down below.
I'm trying to add a button that inserts text that is editable and can be resized within the canvas element.
I have tried many options, but found no success. Is there a way to do that in Javascript?
The code I have:
<head>
<meta charset="utf-8">
<title>
Web Paint!
</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
#draw{
border-color: yellow;
}
</style>
</head>
<body>
<input id="hex" placeholder="enter hex color"></input>
<canvas id="draw"></canvas>
<script>
var canvas = document.getElementById("draw");
var ctx = canvas.getContext("2d");
//resize();
// resize canvas when window is resized
function resize() {
ctx.canvas.width = window.innerWidth;
ctx.canvas.height = window.innerHeight;
}
// initialize position as 0,0
var pos = { x: 0, y: 0 };
// new position from mouse events
function setPosition(e) {
pos.x = e.clientX-160;
pos.y = e.clientY-5;
}
function draw(e) {
if (e.buttons !== 1) return; // if mouse is not clicked, do not go further
var color = document.getElementById("hex").value;
ctx.beginPath(); // begin the drawing path
ctx.lineWidth = 20; // width of line
ctx.lineCap = "round"; // rounded end cap
ctx.strokeStyle = color; // hex color of line
ctx.moveTo(pos.x, pos.y); // from position
setPosition(e);
ctx.lineTo(pos.x, pos.y); // to position
ctx.stroke(); // draw it!
}
// add window event listener to trigger when window is resized
window.addEventListener("resize", resize);
// add event listeners to trigger on different mouse events
document.addEventListener("mousemove", draw);
document.addEventListener("mousedown", setPosition);
document.addEventListener("mouseenter", setPosition);
</script>
</body>
I need to prevent the cursor from going out of the window.
I've read that it's not possible, however I've already done that with a WebGL export from a Unity project. You first had to click the canvas, then the browser would show you a notification saying that you should press 'escape' to exit and get your cursor back.
Since a Unity WebGL canvas can do it, I assume it can be done without Unity?
Use the HTML5 Pointer Lock API
https://developer.mozilla.org/en-US/docs/Web/API/Pointer_Lock_API
Not my code example below, all creds to
https://github.com/mdn/dom-examples/tree/master/pointer-lock
HTML
<!DOCTYPE HTML>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<title>Pointer lock demo</title>
<link type="text/css" rel="stylesheet" href="style.css">
</head>
<body>
<div class="information">
<h1>Pointer lock demo</h1>
<p>This demo demonstrates usage of the pointer lock API. Click on the canvas area and your mouse will directly control the ball inside the canvas, not your mouse pointer. You can press escape to return to the standard expected state.</p>
</div>
<canvas width="640" height="360">
Your browser does not support HTML5 canvas
</canvas>
<div id="tracker"></div>
<script src="app.js"></script>
</body>
</html>
JS
// helper function
const RADIUS = 20;
function degToRad(degrees) {
var result = Math.PI / 180 * degrees;
return result;
}
// setup of the canvas
var canvas = document.querySelector('canvas');
var ctx = canvas.getContext('2d');
var x = 50;
var y = 50;
function canvasDraw() {
ctx.fillStyle = "black";
ctx.fillRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = "#f00";
ctx.beginPath();
ctx.arc(x, y, RADIUS, 0, degToRad(360), true);
ctx.fill();
}
canvasDraw();
// pointer lock object forking for cross browser
canvas.requestPointerLock = canvas.requestPointerLock ||
canvas.mozRequestPointerLock;
document.exitPointerLock = document.exitPointerLock ||
document.mozExitPointerLock;
canvas.onclick = function() {
canvas.requestPointerLock();
};
// pointer lock event listeners
// Hook pointer lock state change events for different browsers
document.addEventListener('pointerlockchange', lockChangeAlert, false);
document.addEventListener('mozpointerlockchange', lockChangeAlert, false);
function lockChangeAlert() {
if (document.pointerLockElement === canvas ||
document.mozPointerLockElement === canvas) {
console.log('The pointer lock status is now locked');
document.addEventListener("mousemove", updatePosition, false);
} else {
console.log('The pointer lock status is now unlocked');
document.removeEventListener("mousemove", updatePosition, false);
}
}
var tracker = document.getElementById('tracker');
var animation;
function updatePosition(e) {
x += e.movementX;
y += e.movementY;
if (x > canvas.width + RADIUS) {
x = -RADIUS;
}
if (y > canvas.height + RADIUS) {
y = -RADIUS;
}
if (x < -RADIUS) {
x = canvas.width + RADIUS;
}
if (y < -RADIUS) {
y = canvas.height + RADIUS;
}
tracker.textContent = "X position: " + x + ", Y position: " + y;
if (!animation) {
animation = requestAnimationFrame(function() {
animation = null;
canvasDraw();
});
}
}
I want the HTML5 canvas to never end so that the square never stops moving, it keeps on "running" so that it can jump over obstacles and the score increases etc. I really do not know how to do this. Please help and thanks in advance. I have posted my code below for everyone to see, I incorporated the JS into the HTML, yep.
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href="style.css">
<meta charset="UTF-8">
<title>Move Square</title>
</head>
<body>
<div id="centre">
<canvas id="myCanvas" height="100px" width="200px"></canvas>
</div>
<script>
function draw(){
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
ctx.beginPath();
ctx.fillStyle = "grey";
ctx.fillRect(0,0,300,300);
ctx.fillRect(0,0,300,300);
ctx.closePath();
x+=dx/4;
//Draw Square
ctx.fillStyle = "red";
ctx.fillRect(x,y,20,20);
clearRect(0, 0, canvas.width, canvas.height);
}
var x = 20;
var y = 20;
var dx = 5;
var dy = 5;
setInterval(draw,10);
document.addEventListener("keydown", keyDownHandler, false);
document.addEventListener("keyup", keyUpHandler, false);
function keyDownHandler(e) {
if(e.keyCode == 39) {
x+=dx;
}
}
</script>
</body>
</html>
You need to make every other object on the canvas move backward if you want your block to run endlessly "forward." Of course, to do this you would need to add another object for reference.
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href="style.css">
<meta charset="UTF-8">
<title>Move Square</title>
</head>
<body>
<div id="centre">
<canvas id="myCanvas" height="100px" width="200px"></canvas>
</div>
<script>
function draw(){
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
ctx.beginPath();
ctx.fillStyle = "grey";
ctx.fillRect(0,0,300,300);
ctx.fillRect(0,0,300,300);
ctx.closePath();
//Draw Square
ctx.fillStyle = "red";
ctx.fillRect(x,y,20,20);
//Two extra green squares
ctx.fillStyle = "green";
ctx.fillRect(x2,50,20,20);
ctx.fillRect(x3,50,20,20);
//make them move backwards at the same speed
x2 -= dx/4;
x3 -= dx/4;
}
var x = 20;
var y = 20;
var dx = 5;
var dy = 5;
//X coordinates for green blocks:
var x2 = 50;
var x3 = 250;
setInterval(draw,10);
document.addEventListener("keydown", keyDownHandler, false);
//document.addEventListener("keyup", keyUpHandler, false);
function keyDownHandler(e) {
if(e.keyCode == 39) {
x+=dx;
}
}
</script>
</body>
</html>
I am trying to animate a line in HTML5 canvas. The line is supposed to move according to the keyboard strokes (just as the red square). Unfortunately it gets longer but it should just move sideways...
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href="style.css">
<title>Test</title>
</head>
<body onload="init();">
<canvas id="myCanvas" width="600" height="400">Your browser does not support the canvas tag.</canvas>
<script>
var canvas;
var ctx;
var incrementX = 0;
var x = 250;
var y = 350;
function init() {
// This function is called after the page is loaded
// 1 - Get the canvas
canvas = document.getElementById('myCanvas');
// 2 - Get the context
ctx = canvas.getContext('2d');
// 3 add key listeners to the window element
window.addEventListener('keydown', handleKeydown, false);
window.addEventListener('keyup', handleKeyup, false);
// 4 - start the animation
requestId = requestAnimationFrame(animationLoop);
}
function handleKeydown(evt) {
if (evt.keyCode === 37) {
//left key
incrementX = -1;
} else if (evt.keyCode === 39) {
// right key
incrementX = 1;
}
}
function handleKeyup(evt) {
incrementX = 0;
}
function animationLoop() {
// 1 - Clear
ctx.clearRect(0, 0, canvas.width, canvas.height);
// 2 Draw
drawLine(x, y);
// 3 Move
x += incrementX;
// call again mainloop after 16.6 ms (60 frames/s)
requestId = requestAnimationFrame(animationLoop);
}
function drawLine(x, y) {
ctx.save();
ctx.translate(x, y);
ctx.moveTo(0,0);
ctx.lineTo(100,0);
ctx.stroke();
ctx.fillStyle='red';
ctx.fillRect(35,30,20,20);
ctx.restore();
}
</script>
</body>
</html>