Rotate picture according to Cursor move direction - javascript

I am trying to rotate a picture according the direction in which the cursor is moved.
Here is some code, I wrote for trying:
<html>
<head>
<meta charset="UTF-8">
<script language="javascript" type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.7.3/p5.min.js"></script>
<!-- uncomment lines below to include extra p5 libraries -->
<!--<script language="javascript" src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.7.3/addons/p5.dom.min.js"></script>-->
<!--<script language="javascript" src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.7.3/addons/p5.sound.min.js"></script>-->
<script language="javascript" type="text/javascript" src="asd.js"></script>
</head>
<body>
</body>
</html>
My JavaScript file is as follows:
function preload() {
arrowImg = loadImage("fish.png");
}
// Creating canvas
function setup() {
createCanvas(600, 300);
background(255);
noCursor();
}
// Displaying the functions above
function draw() {
background(255);
imageMode(CENTER);
image(arrowImg, mouseX, mouseY, arrowImg.width / 10, arrowImg.height / 10);
}
How is it possible to get the attributes in what direction the cursor or mouse is moving in processing/p5js and how is it possible to rotate a picture 180 degrees?
The idea was: the image is following the cursor. If the cursor moves right, the image is staying as it is. the cursor moves left, the image rotates 180 degree

I’m not quite sure i,ve understood your problem but i think that you can add rotate() function from p5js before you draw the image.
About the rotation relatively with your mouse position you can save the coordonates of the mouse and make some simple math with cartesian coordonates to calculate the angle you need.

I have same questions.
after a fews hours researched, I found this way:
let fish;
function preload() {
fish = loadImage('images/fish.png');
}
function setup() {
createCanvas(600, 600);
}
function draw() {
background(0);
var imgx = 300;
var imgy = 300;
var angle = atan2(mouseY - imgy, mouseX - imgx);
push();
translate(imgx, imgy);
rotate(angle);
imageMode(CENTER);
image(fish, 0, 0, 80, 50)
pop();
}
The key point here are imageMode(CENTER);:
translate(imgx, imgy);
rotate(angle);
imageMode(CENTER);
Hope it help. Thanks

Related

How to shift an array of posenet points?

I'm a beginner at using p5.js but I'm currently currently attempting to create a brush sketch like this
ellipse brush
though using computer vision & posenet nose tracking (essentially a nose brush)
The problem is, while it doesn't state any errors, it doesn't work.
This is my code for the ellipse brush without posenet & camera vision
let mousePosition = [];
function setup() {
createCanvas(400, 400);
}
function draw() {
background(0);
//Every frame of animation
//storing the mouse position in an array
mousePosition.push({x: mouseX, y: mouseY});
//shift the array so that the older ones deletes itself
if(mousePosition.length > 100) mousePosition.shift();
//loop
for(let i = 0; i < mousePosition.length; i++) {
//if the variable is less than 50, loop function
let x = mousePosition[i].x;
let y = mousePosition[i].y;
ellipse(x, y, r,r);
var r = 20
}
}
<!DOCTYPE html>
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.5.11/p5.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.5.11/addons/p5.dom.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.5.11/addons/p5.sound.min.js"></script>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<script src="sketch.js"></script>
</body>
</html>
and this is the one with computer vision & nose tracking w/ posenet
let capture;
let poseNet;
let pose;
let text;
let pg;
let nosePosition = []
function setup() {
createCanvas(700, 700);
capture = createCapture(VIDEO);
capture.hide();
pg = createGraphics(width, height);
poseNet = ml5.poseNet(capture, modelLoaded);
poseNet.on('pose', gotPoses);
// background(255)
// color picker
}
function gotPoses(poses) {
//console.log(poses);
if (poses.length > 0) {
pose = poses[0].pose;
}
}
function modelLoaded() {
console.log('poseNet.ready');
}
function draw() {
translate(width, 0); // move to far corner
scale(-1.0, 1.0); // flip x-axis backwards
image(capture, 0, 0, width, width * capture.height /
capture.width);
image(pg, 0, 0, width, height);
if (pose) {
nosePosition.push({x:pose.nose.x ,y: pose.nose.y});
if(nosePosition.length > 100) nosePosition.shift(); {
}
for(let i = 0; i < nosePosition.length; i++) {
//if the variable is less than 50, loop function
let x = nosePosition[i].x;
let y = nosePosition[i].y;
pg.ellipse(x, y, i/5,i/5);
var r = 20 //how big the ellipse is
pg.fill(255)
pg.noStroke();
}
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.1.9/p5.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.1.9/addons/p5.sound.min.js"></script>
<script src="https://unpkg.com/ml5#latest/dist/ml5.min.js" type="text/javascript"></script>
<link rel="stylesheet" type="text/css" href="style.css">
<meta charset="utf-8" />
</head>
<body>
<script src="sketch.js"></script>
</body>
</html>
The second is essentially very similar to the first, as I've only changed the mouseX/Ys into the posenet Nose keypoint.
Any insight/solution would be highly appreciated!
Thank you :)
You're shifting properly, but you forgot to clear the pg graphic, which is kind of like forgetting to put background(0) in your original sketch. So instead of drawing all the ellipses on a blank background, you're drawing them on top of the previous frame.
Adding pg.clear() anywhere in draw() after you display pg on the canvas (image(pg, ...)) and before you draw the ellipses (for (...) {... ellipse(nosePosition[i].x...)}) should do the trick. Here's where I put it:
image(pg, 0, 0, width, height);
pg.clear();//HERE
if (pose) {//...

Paper.js, gap between cursor and canvas

I am trying to build a simple drawing app with Paper.js. I can draw with the mouse but I have a gap between the cursor and the line drawn on the canvas.
I have realised that the navigation menu on top of the webpage is pushing down the cursor (100px) I assume that the mouse coordinates are taken from top-left (0-0) of the window and the same coordinates are used on the canvas which measured these points from its own top-left corner (see the screenshot). I have tried setting the canvas position to absolute, which helps to get it to the top left corer, but I need it in the center of the window.
How could I fix this?
Thanks!
script:
...
var doc = $(document),
win = $(window),
canvas = $('#paper'),
ctx = canvas[0].getContext('2d')
doc.on('mousemove',function(e){
if($.now() - lastEmit > 30){
socket.emit('mousemove',{
'x': e.pageX,
'y': e.pageY,
'drawing': drawing,
'id': id
});
lastEmit = $.now();
}
// Draw a line for the current user's movement, as it is
// not received in the socket.on('moving') event above
// (because he only broadcats (not receiving))
if(drawing){
drawLine(prev.x, prev.y, e.pageX, e.pageY);
prev.x = e.pageX;
prev.y = e.pageY;
}
});
function drawLine(fromx, fromy, tox, toy){
console.log(fromy + ' ' + toy);
ctx.moveTo(fromx, fromy);
ctx.lineTo(tox, toy);
ctx.stroke();
}
I can repro your issue by using an early version of paperjs - notably this version is the one on jsfiddle. I see the lines offset the way you do with v 0.22 and then correctly rendered with version 0.9.25. Here's my code:
<!-- fails -->
<script type='text/javascript' src='http://cdnjs.cloudflare.com/ajax/libs/paper.js/0.22/paper.js'></script>
<!-- works --> <!--
<script type='text/javascript' src='https://cdnjs.cloudflare.com/ajax/libs/paper.js/0.9.25/paper-full.js'></script>
-->
<style type='text/css'>
#canvas1{
height: 400px;
width: 400px;
border: 1px solid black;
}
</style>
<script type='text/javascript'>
paper.install(window);
window.onload = function() {
paper.setup('canvas1');
var path = new Path();
var tool = new Tool();
path.strokeColor = 'black';
tool.onMouseMove = function(event) {
path.add(event.point);
}
}
</script>

What does beginPath() and closePath() do exactly?

The question that I have is with context.beginPath() and context.closePath(). The code below will draw a circle in an arc around the screen until it disappears followed by a small dot which I would comment out because it is a .jpg which I do not know how to include.
My question is exactly what does the beginPath() do and also the closePath() do?
If I comment them out I get a wild result other than what I am expecting. I have looked on the internet but I have not seen the results like this.
Code with a question:
function drawTheBall() {
context.fillStyle = "#00AB0F"; //sets the color of the ball
context.beginPath();
context.arc(ball.x,ball.y,10,0,Math.PI*2,true); //draws the ball
context.closePath();
context.fill();
}
Working code below
HTML-Javascript
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>CH5EX10: Moving In Simple Geometric Spiral </title>
<script src="modernizr.js"></script>
<script type="text/javascript">
window.addEventListener('load', eventWindowLoaded, false);
function eventWindowLoaded() {
canvasApp();
}
function canvasSupport () {
return Modernizr.canvas;
}
function canvasApp() {
var radiusInc = 2;
var circle = {centerX:250, centerY:250, radius:2, angle:0, radiusInc:2}
var ball = {x:0, y:0,speed:.1};
var points = new Array();
theCanvas = document.getElementById('canvasOne');
context = theCanvas.getContext('2d');
var pointImage = new Image();
pointImage.src = "point.png"; <-- Comment this line out
if (!canvasSupport()) {
return;
}
function erraseCanvas() {
context.clearRect(0,0,theCanvas.width,theCanvas.height);
}
function drawPathPoints() {
//Draw points to illustrate path
points.push({x:ball.x,y:ball.y});
for (var i= 0; i< points.length; i++) {
context.drawImage(pointImage, points[i].x, points[i].y,1,1);
}
}
function drawTheBall() {
context.fillStyle = "#00AB0F"; //sets the color of the ball
context.beginPath();
context.arc(ball.x,ball.y,10,0,Math.PI*2,true); //draws the ball
context.closePath();
context.fill();
}
function buildBall() {
ball.x = circle.centerX + Math.cos(circle.angle) * circle.radius;
ball.y = circle.centerY + Math.sin(circle.angle) * circle.radius;
circle.angle += ball.speed;
circle.radius += radiusInc;
}
function drawScreen () {
erraseCanvas();
buildBall();
drawPathPoints();
drawTheBall();
}
function gameLoop() {
window.setTimeout(gameLoop, 20);
drawScreen()
}
gameLoop();
}
</script>
</head>
<body>
<div style="position: absolute; top: 50px; left: 50px;">
<canvas id="canvasOne" width="500" height="500">
Your browser does not support the HTML 5 Canvas.
</canvas>
</div>
</body>
</html>
beginPath()
beginPath() clears the current internal path object and its sub-paths, which accumulates path operations such as line, rect, arc, arcTo and so on, regardless of if they are filled or stroked.
closePath()
closePath() connects the current path, or sub-path, position with the first point on that path created either with beginPath() or moveTo() if that was used. The latter creates a sub-path on the current main path and only this sub-path gets closed.
Some methods do a closePath() implicit and temporary for you such as fill() and clip() which means it's not needed for those calls. In any case, it must be called before a stroke() (or fill(), if you chose to use that) is called.
One can perhaps understand this method better if one think of it as "closing the loop" rather than ending or closing the path [object] which it doesn't.
BeginPath will start a new path, unlike moveTo which will begin a new subpath
Close path will close the path. it probably isn't needed unless you want stroking to stroke the entire path without a gap
Close Path:
//An Open Box
ctx.moveTo(0 , 0);
ctx.lineTo(0 , 100);
ctx.lineTo(100, 100);
ctx.lineTo(100, 0);
ctx.stroke();
ctx.translate(150, 0);
//A closed box
ctx.moveTo(0 , 0);
ctx.lineTo(0 , 100);
ctx.lineTo(100, 100);
ctx.lineTo(100, 0);
ctx.closePath();
ctx.stroke();

Draw HTML5 Canvas pulse line

Hey guys I've been trying to wrap my head around the HTML5 Canvas animation but failed miserably I wanted to achieve the below figure by animating this custom shape in an interval of 10 seconds.
I've pretty much screwed the math of it so I ended up just writing every lineTo statement manually, tried Paul Irish's requestAnimationFrame at the end to animate the line but no luck.
Any help would be highly appreciated, here is
thelive demo
Thanks guys
It's not moving cause you are basically not moving anything - the same shape is drawn to the same position each iteration.
Here is a modified version which animates the pulse to the left (adjust dlt to change speed):
Modified fiddle here
var segX = canvas.width / 6;
var segY = canvas.height / 2;
function draw() {
ctx.clearRect(0,0,canvas.width, canvas.height);
ctx.beginPath();
ctx.moveTo(0, segY);
for(var i = dlt, h = true; i < canvas.width + segX; i += segX) {
if (h) {
ctx.lineTo(i, segY);
ctx.lineTo(i, segY + segX);
} else {
ctx.lineTo(i, segY + segX);
ctx.lineTo(i, segY);
}
h = !h;
}
ctx.stroke();
dlt--;
if (dlt < -segX * 2) dlt = 0;
requestAnimFrame(draw);
}
You're basically needing a function that returns only 2 values--high and low.
Here's a function that returns only low/high values based on a period and oscillation values:
// squared wave
// p = period (how long it takes the wave to fully complete and begin a new cycle)
// o = oscillation (change in wave height)
function squareY(x) {
return( (x%p)<o?o:0 );
}
Demo: http://jsfiddle.net/m1erickson/A69ZV/
Example code:
<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" media="all" href="css/reset.css" />
<script src="http://code.jquery.com/jquery.min.js"></script>
<style>
body{ background-color: ivory; }
canvas{border:1px solid red;}
</style>
<script>
$(function(){
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
ctx.lineWidth=3;
var p=30; // period
var o=15; // oscillation
var fps = 60;
var n=0;
animate();
function animate() {
setTimeout(function() {
requestAnimationFrame(animate);
// Drawing code goes here
n+=1.5;
if(n>300){
n=0;
}
ctx.clearRect(0,0,canvas.width,canvas.height);
ctx.beginPath();
for(var x=0;x<n;x++){
var y=squareY(x);
ctx.lineTo(x,y+50);
}
ctx.stroke();
}, 1000 / fps);
}
// squared sine
function squareY(x) {
return( (x%p)<o?o:0 );
}
}); // end $(function(){});
</script>
</head>
<body>
<canvas id="canvas" width=350 height=350></canvas>
</body>
</html>

Drawing to canvas like in paint

I have three arrys:
clickX = [],
clickY = [],
clickDrag = [];
this is what happens when you click down:
$('#canvasCursor').mousedown(function (e) {
console.log('down');
mouseX = e.pageX - this.offsetLeft;
mouseY = e.pageY - this.offsetTop;
paint = true;
addClick(e.pageX - this.offsetLeft, e.pageY - this.offsetTop);
redraw();
});
here it adds the clicks to the array and draws.:
function redraw() {
ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height); // Clears the canvas
ctx.strokeStyle = "green";
ctx.lineJoin = "round";
ctx.lineWidth = brushSize*2;
for (var i = 0; i < clickX.length; i++) {
ctx.beginPath();
if (clickDrag[i] && i) {
ctx.moveTo(clickX[i - 1], clickY[i - 1]);
} else {
ctx.moveTo(clickX[i] - 1, clickY[i]);
}
ctx.lineTo(clickX[i], clickY[i]);
ctx.closePath();
ctx.stroke();
}
}
I am trying to get rid of the array way of doing it now because when I change the var brushSize dynamically using a slider it redraws the entire picture in the new size not the size they had at the time. I don't know how to save the size of any specific object in the array and then paint them seperate.
I don't mind if I cant implement the undo function that this way gives me as long as I can fix the change of brush size. Here you can see what I am rambling on about! http://www.taffatech.com/Paint.html
-also it seems slower and im guessing its because its drawing from an array
Do not store painting to array
It slows down drawing critically. Just draw the latest line without clearing canvas. That way lineWeight changes does not affect to before drawings. So remove ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height); and for loop. You also might want to change context styles (lineWidth etc.) only when changes occur, not every time you run redraw() function.
Undo support
Making different canvas for every mouse down session and drawing them together you can easily make undo feature. By pressing undo it simply splices latest canvas out of canvases array. Google to learn more about drawing to temporary canvas.
EDIT: Sorry, fixed some typos
Edit 2: And again. It's a bit difficult to test.
There's no reason to redraw each of the points each time. You could modify your listener to do this:
var prevMouseX=null,prevMouseY=null;
$('#canvasCursor').mousedown(function (e) {
paint = true;
console.log('down');
//get current mouse coords
mouseX = e.pageX - this.offsetLeft;
mouseY = e.pageY - this.offsetTop;
if (prevMouseX==null) {
//store these coordinates for next time if they haven't been defined yet
prevMouseX = mouseX;
prevMouseY = mouseY;
}
});
$('#canvasCursor').mousemove(function (e) {
//get current mouse coords
mouseX = e.pageX - this.offsetLeft;
mouseY = e.pageY - this.offsetTop;
if (prevMouseX==null) {
//store these coordinates for next time if they haven't been defined yet
prevMouseX = mouseX;
prevMouseY = mouseY;
}
if (paint) {drawline(mouseX,mouseY,prevMouseX,prevMouseY);}
//store these coordinates for next time
prevMouseX = mouseX;
prevMouseY = mouseY;
});
Where the function drawLine is defined as:
function drawline(x1,y1,x2,y2) {
ctx.strokeStyle = "green";
ctx.lineJoin = "round";
ctx.lineWidth = brushSize*2;
ctx.beginPath();
ctx.moveTo(x1,y1);
ctx.lineTo(x2,y2);
ctx.closePath();
ctx.stroke();
}
Here’s how to use canvas to draw like Paint
If you want an undo feature, your best option is to record all line segments drawn by the user.
This is done with a point array that contains all points (polylines) drawn by the user.
To track the brush size and brush color, you need to include this info in your array also.
So each element of the the array will have this info about each line segment:
x: the ending x coordinate of this line segment
y: the ending y coordinate
size: the brush size (lineWidth)
color: the brush color (strokeStyle)
mode: “begin” indicates the beginning of a new line, “end” indicates the end of this line.
How does it work?
When the user is drag-drawing a line segment, each mousemove event is extending the current segment with context.lineTo and context.stroke.
When the user selects a new BrushSize or BrushColor, context.beginPath starts context.beginPath.
When the user holds down the Undo button, the last point in the last line segment is popped off the point array. Then all the surviving line segments are redrawn. The undo button fires every 1/10th of a second when held down.
Here is code and a Fiddle: http://jsfiddle.net/m1erickson/AEYYq/
<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" media="all" href="css/reset.css" /> <!-- reset css -->
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<!--[if lt IE 9]><script type="text/javascript" src="../excanvas.js"></script><![endif]-->
<style>
body{ background-color: ivory; }
canvas{border:1px solid red;}
</style>
<script>
$(function(){
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var lastX;
var lastY;
var mouseX;
var mouseY;
var canvasOffset=$("#canvas").offset();
var offsetX=canvasOffset.left;
var offsetY=canvasOffset.top;
var isMouseDown=false;
var brushSize=20;
var brushColor="#ff0000";
var points=[];
function handleMouseDown(e){
mouseX=parseInt(e.clientX-offsetX);
mouseY=parseInt(e.clientY-offsetY);
// Put your mousedown stuff here
ctx.beginPath();
if(ctx.lineWidth!=brushSize){ctx.lineWidth=brushSize;}
if(ctx.strokeStyle!=brushColor){ctx.strokeStyle=brushColor;}
ctx.moveTo(mouseX,mouseY);
points.push({x:mouseX,y:mouseY,size:brushSize,color:brushColor,mode:"begin"});
lastX=mouseX;
lastY=mouseY;
isMouseDown=true;
}
function handleMouseUp(e){
mouseX=parseInt(e.clientX-offsetX);
mouseY=parseInt(e.clientY-offsetY);
// Put your mouseup stuff here
isMouseDown=false;
points.push({x:mouseX,y:mouseY,size:brushSize,color:brushColor,mode:"end"});
}
function handleMouseMove(e){
mouseX=parseInt(e.clientX-offsetX);
mouseY=parseInt(e.clientY-offsetY);
// Put your mousemove stuff here
if(isMouseDown){
ctx.lineTo(mouseX,mouseY);
ctx.stroke();
lastX=mouseX;
lastY=mouseY;
// command pattern stuff
points.push({x:mouseX,y:mouseY,size:brushSize,color:brushColor,mode:"draw"});
}
}
function redrawAll(){
if(points.length==0){return;}
ctx.clearRect(0,0,canvas.width,canvas.height);
for(var i=0;i<points.length;i++){
var pt=points[i];
var begin=false;
if(ctx.lineWidth!=pt.size){
ctx.lineWidth=pt.size;
begin=true;
}
if(ctx.strokeStyle!=pt.color){
ctx.strokeStyle=pt.color;
begin=true;
}
if(pt.mode=="begin" || begin){
ctx.beginPath();
ctx.moveTo(pt.x,pt.y);
}
ctx.lineTo(pt.x,pt.y);
if(pt.mode=="end" || (i==points.length-1)){
ctx.stroke();
}
}
ctx.stroke();
}
function undoLast(){
points.pop();
redrawAll();
}
ctx.lineJoin = "round";
ctx.fillStyle=brushColor;
ctx.lineWidth=brushSize;
$("#brush5").click(function(){ brushSize=5; });
$("#brush10").click(function(){ brushSize=10; });
// Important! Brush colors must be defined in 6-digit hex format only
$("#brushRed").click(function(){ brushColor="#ff0000"; });
$("#brushBlue").click(function(){ brushColor="#0000ff"; });
$("#canvas").mousedown(function(e){handleMouseDown(e);});
$("#canvas").mousemove(function(e){handleMouseMove(e);});
$("#canvas").mouseup(function(e){handleMouseUp(e);});
// hold down the undo button to erase the last line segment
var interval;
$("#undo").mousedown(function() {
interval = setInterval(undoLast, 100);
}).mouseup(function() {
clearInterval(interval);
});
}); // end $(function(){});
</script>
</head>
<body>
<p>Drag to draw. Use buttons to change lineWidth/color</p>
<canvas id="canvas" width=300 height=300></canvas><br>
<button id="undo">Hold this button down to Undo</button><br><br>
<button id="brush5">5px Brush</button>
<button id="brush10">10px Brush</button>
<button id="brushRed">Red Brush</button>
<button id="brushBlue">Blue Brush</button>
</body>
</html>
I took this question and used it to create a full featured "coloring book" solution, which I posted on Github. https://github.com/collinph/jl-coloringbook
It handles all of the mouse issues + undo and other things that we were discussing + a lot of sizing issues that could come up. It does store the coordinates in an array and is not slow as some suggested it would be-- not in Chrome or Safari anyway.

Categories