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>
Related
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>
I'm currently trying to get a similar touch/stylus behaviour to Squid (the notetaking app). I have used the PointerEvent API and it all works, except for one annoying issue:
After I put down the stylus or the finger, it draws a stroke for the next ~0.3 seconds, but after that, no more pointermove events are fired as long as the pointer is down.
here's my code:
index.html
<!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>Draw</title>
<link rel="stylesheet" href="index.css">
</head>
<body>
<canvas id="canvas" width="500px" height="500px" style=" position: absolute;border: 2px solid red;"></canvas>
<script src="index.js"></script>
</body>
</html>
index.js
var canvas = document.querySelector("#canvas");
var ctx = canvas.getContext("2d");
ctx.fillStyle = "white"
var pos = {}
canvas.addEventListener("pointerdown", function (e) {
pos.x = e.pageX;
pos.y = e.pageY;
});
canvas.addEventListener("pointermove", function (e) {
console.log(e.pressure)
switch (e.pointerType) {
case "pen":
ctx.beginPath();
ctx.moveTo(pos.x, pos.y);
ctx.lineTo(e.pageX, e.pageY);
ctx.stroke();
pos.x = e.pageX;
pos.y = e.pageY;
break;
case "touch":
ctx.fillRect(e.pageX - 10, e.pageY - 10, 20, 20);
break;
}
});
index.css is just a css reset
I'm really confused over this and can't seem to find anyone else who had this problem. Any help would be appreciated!
Just add touch-action: none; to your canvas's style attribute.
After ~0.3 seconds starts touch events as page scrolling.
I've got following HTML:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<script>
var w = window.screen.width;
var h = window.screen.height;
var s = "Width: " + w + "px<br/>Height: " + h + "px";
document.body.innerHTML = s;
</script>
</body>
</html>
Using Pixel 2 with Chrome gives me result:
Width: 412px
Height: 732px
And with Firefox, I got result:
Width: 414px
Height: 688px
Why the result are not the same? It looks to me that Firefox has not correct dimensions.
Trying to move my div randomly around page. Currently new randomly generated div appears on new location on page as opposed to transitioning to new position (I want div to track across page instead of deleting itself and reappearing).
function randomdiv1 () {
var divnum = $('.random').length;
var random = $('.random');
var startleft =random.css('left', (Math.floor(Math.random() * ($(window).width()-50))));
var starttop =random.css('top', (Math.floor(Math.random() * ($(window).height()-50))));
return [startleft, starttop];
}
function randomdiv2 () {
var divnum = $('.random').length;
var random = $('.random');
var endleft =random.css('left', (Math.floor(Math.random() * ($(window).width()-50))));
var endtop =random.css('top', (Math.floor(Math.random() * ($(window).height()-50))));
return [endleft, endtop];
}
function randomdiv3 () {
var startdiv = randomdiv1 ();
var enddiv = randomdiv2 ();
$('.random').animate({
top: enddiv[1],
left: enddiv[0],
}, 2000, 'swing', randomdiv3);
}
randomdiv3 ();
.random {
width: 50px;
height: 50px;
background-color: blue;
position: absolute;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title></title>
<link rel="stylesheet" href="style.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script src="script.js"></script>
</head>
<body>
<div class="random"></div>
</body>
</html>
This can be achieved in a simple way by adding the following css property to .random:
transition: left 2s, top 2s;
https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Transitions/Using_CSS_transitions
Example below:
https://jsfiddle.net/4r9xch2v/
I started designing my own site and followed a YouTube video tutorial on how to code Motion Parallax scrolling on Dreamweaver using JavaScript and CSS so I followed the video and did everything it told me to but my code is still not working?
https://www.youtube.com/watch?v=cF3oyFXjRWk
I feel like my JavaScript code is not linked or something because some of the syntax or variables that are highlighted in a specific color on the video are not highlighted for me. What could my problem be?
I put the JavaScript within the head tag as well... this is the .js code
<script type="text/javascript">
var ypos, image;
function parallex () {
ypos = window.pageYOffset;
image = document.getElementById('background');
image.style.top = ypos * .4 + 'px';
}
window.addEventListener('scroll', parallex);
</script>
This is all my code with the css as well....
<!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">
<title>Bootstrap 101 Template</title>
<link href="../Tezel's Website/css/bootstrap.min.css" rel="stylesheet">
<style type="text/css">
*{
margin: 0px;
padding: 0px;
}
#image{
position: relative;
z-index: -1
}
#content{
height: 750px;
width: 100%;
margin-top: -10px;
background-color:#4dbbac;
position: relative;
z-index: 1;
}
</style>
<script type="text/javascript">
var ypos, image;
function parallex () {
ypos = window.pageYOffset;
image = document.getElementById('background');
image.style.top = ypos * .4 + 'px';
}
window.addEventListener('scroll', parallex);
</script>
</head>
<body>
<img id = "background" src = "sky1.jpg" width = "100%" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="../Tezel's Website/js/bootstrap.min.js"></script>
<div class = "main">
<div id = "container">
<div class = "header">
<div id = "content">
</div>
</div>
</div>
</div>
</body>
</html>
This is not looking quite charming:
<script src="../Tezel's Website/js/bootstrap.min.js"></script>
Check if all resources are loaded. Right click and check element or inspect element in your browser. Make sure all resources are found and loaded.