HTML5 - Canvas Element & Custom Cursor - javascript

HTML5 document - Canvas Element is not running the JavaScript parameters for the customized 'rectangle' cursor. HELP PLEASE :)
<head>
<title>Canvas Element & Custom Cursor</title>
</head>
<body id="body" style="background-color:red;">
<canvas id="canvas" width="600" height="400" style="background-
color:white;"> </canvas>
<script>
funtion CanvasProperties(){
var canvas = document.getElementById("canvas");
canvas = canvas.getContext("2d");
window.addEventListener("mousemove", CustomCursor, false);}
function CustomCursor(){
canvas.clearRect(0,0,600,400);
var xPosition = clientX;
var yPosition = clientY;
canvas.fillRect(xPosition, yPosition, 100, 100);}
window.addEventListener("load", CanvasProperties, false);
</script>
</body> </html>

There are several issues here, some already pointed out in Scimonster's answer, but an important one remains.
For the rectangle to be placed correctly you need to "correct" the mouse positions. The mouse positions are relative to client window while you will need them relative to canvas element.
Also, you are overriding canvas with context. Use a separate variable for it, and place those in global (parent) scope.
Here is a full version (inside the script tags):
var canvas, context; // place this in global scope
function CanvasProperties(){
canvas = document.getElementById("canvas");
context = canvas.getContext("2d"); // separate var for context...
window.addEventListener("mousemove", CustomCursor, false);
}
function CustomCursor(e){
var canvasRect = canvas.getBoundingClientRect(); // get position of canvas element
var xPosition = e.clientX - canvasRect.left; // adjust mouse positions to
var yPosition = e.clientY - canvasRect.top; // become relative to canvas
context.clearRect(0,0,600,400); // use context
context.fillRect(xPosition - 50, yPosition - 50, 100, 100);
}
window.addEventListener("load", CanvasProperties, false);
<canvas id="canvas" width=600 height=400></canvas>

You're not using the event object at all -- clientX and clientY aren't global properties.
function CustomCursor(event){
canvas.clearRect(0,0,600,400);
var xPosition = event.clientX;
var yPosition = event.clientY;
canvas.fillRect(xPosition, yPosition, 100, 100);}

Thanks, guys! We now have a custom cursor for painting on canvas :)
<!DOCTYPE html>
<html>
<head>
<title>Canvas Element & Custom Cursor</title>
</head>
<body id="body" style="background-color:red;">
<canvas id="canvas" width="600" height="400" style="background-
color:white;"> </canvas>
<script>
var canvas; var context;
function CanvasProperties(){
canvas = document.getElementById("canvas");
context = canvas.getContext("2d");
window.addEventListener("mousemove", CustomCursor, false);}
function CustomCursor(event){
var xPosition = event.clientX;
var yPosition = event.clientY;
context.fillRect(xPosition, yPosition, 100, 100);}
window.addEventListener("load", CanvasProperties, false);
</script>
</body>
</html>

Related

Javascript: How do I zoom in my Canvas so that my functions are still working?

Dear StackOverflow community,
I'm currently working on a project. My goal is to color individual pixels in a zoomed in canvas.
However when I used:
canvas.body.style.width = '600px';
canvas.body.style.height= '300px';
my functions stopped working.
Here is my JavaScript code:
<!DOCTYPE html>
<html>
<meta charset='UTF-8'>
<body>
<canvas id="myCanvas" width="200" height="200" style="border:3px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.</canvas>
<script>
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
var mouseDown = 0;
function mouseDownFunction() {
++mouseDown;
}
function mouseUpFunction() {
--mouseDown;
}
function mouseMoveFunction(e) {
var posX = e.clientX;
var posY = e.clientY;
ctx.fillRect(posX - 10, posY - 10, 100, 100);
}
c.addEventListener("mousedown", function(e){
mouseDownFunction();
this.addEventListener("mousemove", mouseMoveFunction);
});
c.addEventListener("mouseup", function(e){
mouseUpFunction();
this.removeEventListener("mousemove", mouseMoveFunction);
});
c.addEventListener("click", mouseMoveFunction);
c.addEventListener("mouseout",function(e){
this.removeEventListener("mousemove", mouseMoveFunction);
});
c.addEventListener("mouseenter",function(e){
if (mouseDown == 1) {
this.addEventListener("mousemove", mouseMoveFunction);
}});
</script>
</body>
</html>
What's the best practice to zoom in and out of my canvas to allow easy access to individual pixels?
Thanks in advance for your time.
Sincerely,
JavaIsMyBae

Draw on Image loaded inside HTML canvas

I have a HTML canvas in Ionic app.
<canvas id="canvas" color="{{ color }}" width="800" height="600" style="position:relative;"></canvas>
In this canvas, I am loading an image. Below is the code from controller
var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');
var img = new Image();
img.src = $stateParams.imageId;
img.onload = function() {
context.drawImage(img, 0, 0, canvas.width, canvas.height);
}
After the image is loaded, users need the ability to write on the image and circle/highlight certain areas of the image.
Doesn't HTML canvas provide this feature by default? Right now I am not able to annotate anything on the image. How can I achieve this?
You need to implement this yourself.
You can do it by hooking into the mouse click / move events. using your 2d context, draw small rectangle at the mouse's current position if the most moves and the left mouse button is down.
The effect is similar to a Windows paint pencil tool. Here's a simple example.
<html>
<head>
<style>
canvas{
border: 1px solid black;
}
</style>
</head>
<body>
<canvas id="myCanvas"></canvas>
<script>
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
var isMouseDown = false;
canvas.onmousedown = function(e){
isMouseDown = true;
}
canvas.onmouseup = function(e){
isMouseDown = false;
}
canvas.onmousemove = function(e){
if(isMouseDown === false){
return;
}
var canvasPosition = canvas.getBoundingClientRect();
var x = e.clientX - canvasPosition.left;
var y = e.clientY - canvasPosition.top;
ctx.fillRect(x, y, 2, 2);
};
</script>
</body>
</html>

Why the coordinates of mouse in canvas are wrong?

I intend to draw free with the mouse cursor in canvas. My code seems to do the part with color but it doesn't take the exact coordinates of my current mouse position in canvas when i draw.
<body>
<canvas id="canvas" style=" width: 400; height: 400px; background-color:yellow; position: absolute; margin-left:100px; margin-top:30px"></canvas>
<script>
var Color = 'blue';
var Canvas = document.getElementById('canvas');
var Context = Canvas.getContext('2d');
$("canvas").on("mousemove",function(e){
X = e.clientX - canvas.offsetLeft;
Y = e.clientY - canvas.offsetTop;
Context.strokeStyle = Color;
Context.lineWidth = 3;
Context.lineCap = 'round';
Context.beginPath();
Context.moveTo(X,Y);
Context.lineTo(X,Y);
Context.fillRect(X,Y, 3,3)
Context.stroke();
Context.closePath();
});
</script>
</body>
https://jsfiddle.net/93L8mLnf/
I tested in console.log the coordinates and they are corect. I'm confused..
You need to synchronize the dimension of the canvas with the DOM element.
Add this:
Canvas.width = Canvas.clientWidth;
Canvas.height = Canvas.clientHeight;
Demonstration
You'll also notice the canvas isn't blurred anymore.
Note that this must be done every time the canvas DOM element changes size (usually because the window is resized) so when your element isn't of fixed size you should bind an event handler on the window resize event to do that synchronization again (and usually to redraw the content).
You have to add width and height by canvas attributes
see in fiddle
<canvas id="canvas" style="background-color:yellow;" width="250" height="250"></canvas>

Html5 canvas animation. How to reset rectangle when it hits the end

Hey Im experimenting with some html5 animation and so far I have a square that "falls" whenever I press the button. I was wondering how i could have it go back to the top when it hits the bottom and fall again.
My current code is:
<html>
<head>
</head>
<body>
<canvas id="myCanvas" width="200" height="400" style="border:1px solid black;">
Your browser does not support the HTML5 canvas tag.
</canvas>
<script>
function draw (x,y){
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.save();
var side = 10
var up = 10
ctx.clearRect(0,0,200,400);
ctx.fillStyle = "#FF0000";
ctx.fillRect(x,y,up,side);
ctx.restore();
y += 5;
var loopTimer = setTimeout('draw('+x+','+y+')',30);
}
</script>
<button onclick="draw(0,0)">draw</button>
</body>
</html>
Using your variables y, you can simply check if it is below the height of the canvas height.
if( y > c.height ){ // use the canvas height, not the context height
y = 0;
}
Also, the way you're currently calling the timer is a bit inefficient. Instead of :
var loopTimer = setTimeout('draw('+x+','+y+')',30);
I would recommend
var loopTimer = setTimeout(function(){ draw(x,y); },30);
Here's a working example: http://jsfiddle.net/vwcdpLvv/

Mouse position within HTML 5 Canvas

I am writing a simple drawing app to get an understanding of the HTML 5 canvas. The problem is that I simply can't seem to get the correct mouse position within the canvas element.I've looked at the other questions on stackoverflow like the one here getting mouse position with javascript within canvas that address this issue but their solutions don't seem to help me.
Here is my code:
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>Untitled Document</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js" type="text/javascript"></script>
<style type="text/css">
#test {
border: solid black 1px;
width: 500px;
height: 500px;
}
</style>
<script type="text/javascript">
$(function(){
var canvas=document.getElementById('test');
if(canvas.getContext){
var ctx =canvas.getContext('2d');
var draw = false;
ctx.strokeStyle = "rgb(200,0,0)";
ctx.lineWidth = 3;
ctx.lineCap = "round";
$('#test').mousedown(function(){draw=true;});
$('#test').mouseup(function(){draw=false;});
$('#test').mousemove(function(e){
if(draw){
var x , y;
x = e.layerX;
y = e.layerY;
ctx.moveTo(x,y);
ctx.lineTo(x+1,y+1);
ctx.stroke();
}
});
}
});
</script>
</head>
<body>
<canvas id="test"></canvas>
</body>
</html>
What am I doing wrong here? I have tested this in both Chrome/Firefox.
Your canvas is missing width and height properties. In the current solution it just scales the default to fit your CSS. This in turn breaks your mouse coords. Try something along
<canvas id="test" width=500 height=500></canvas>
as your canvas markup.
Suppose your canvas has already been declared...
var Mouse = { //make a globally available object with x,y attributes
x: 0,
y: 0
}
canvas.onmousemove = function (event) { // this object refers to canvas object
Mouse = {
x: event.pageX - this.offsetLeft,
y: event.pageY - this.offsetTop
}
}
Mouse will update when you mouse move on the canvas
You should add pixel dimenstion to your canvas element:
<canvas id="test" width='500px' height='500px' ></canvas>
Here is working example - http://jsfiddle.net/gorsky/GhyPr/.

Categories

Resources