mouse coordinates in canvas not working - javascript

var canvas=document.getElementById('canvas');
var ctx=canvas.getContext("2d");
var mouseX=0;
var mouseY=0;
var canvasPos=getPosition(canvas);
ctx.addEventListener("mousemove",setMousePosition,false);
function getPosition(e1) {
var xPosition = 0;
var yPosition = 0;
while (e1) {
xPosition += (e1.offsetLeft - e1.scrollLeft + e1.clientLeft);
yPosition += (e1.offsetTop - e1.scrollTop + e1.clientTop);
e1 = e1.offsetParent;
}
return { x: xPosition, y: yPosition };
}
function setMousePosition(e) {
mouseX = e.clientX - canvasPos.x;
mouseY = e.clientY - canvasPos.y;
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.beginPath();
ctx.arc(mouseX, mouseY, 50, 0, 2 * Math.PI, true);
ctx.fillStyle = "#FF6A6A";
ctx.fill();
ctx.closePath();
}
function getPosition(e1) {
var xPosition=0;
var yPosition=0;
while(e1) {
xPosition+=(e1.offsetLeft-e1.scrollLeft+e1.clientLeft);
yPosition+=(e1.offsetTop-e1.scrollTop+e1.clientTop);
e1=e1.offsetParent;
}
return {
x: xPosition,
y: yPosition
};
}
<canvas id="canvas"></canvas>
The goal is for a canvas element to follow the mouse movement. My attempt is pasted above. I tried retrieving the exact mouse coordinates and used it to re-draw the element. I don't seem to be getting any output, only a blank canvas. Any help is appreciated.

You had 2 typos:
var context...
ctx.addEventListener(...)
The: ctx.addEventListener() is not possible because of the context has no events.
The canvas does have those.
var canvas=document.getElementById('canvas');
// edit from context to ctx
var ctx=canvas.getContext("2d");
var mouseX=0;
var mouseY=0;
var canvasPos=getPosition(canvas);
// edit ctx to canvas
canvas.addEventListener("mousemove",setMousePosition,false);
function getPosition(e1) {
var xPosition = 0;
var yPosition = 0;
while (e1) {
xPosition += (e1.offsetLeft - e1.scrollLeft + e1.clientLeft);
yPosition += (e1.offsetTop - e1.scrollTop + e1.clientTop);
e1 = e1.offsetParent;
}
return { x: xPosition, y: yPosition };
}
function setMousePosition(e) {
mouseX = e.clientX - canvasPos.x;
mouseY = e.clientY - canvasPos.y;
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.beginPath();
ctx.arc(mouseX, mouseY, 50, 0, 2 * Math.PI, true);
ctx.fillStyle = "#FF6A6A";
ctx.fill();
ctx.closePath();
}
function getPosition(e1) {
var xPosition=0;
var yPosition=0;
while(e1) {
xPosition+=(e1.offsetLeft-e1.scrollLeft+e1.clientLeft);
yPosition+=(e1.offsetTop-e1.scrollTop+e1.clientTop);
e1=e1.offsetParent;
}
return {
x: xPosition,
y: yPosition
};
}
<canvas id="canvas"></canvas>

You've to add event listener to canvas not to its context
var canvas=document.getElementById('canvas');
var ctx=canvas.getContext("2d");
var mouseX=0;
var mouseY=0;
var canvasPos=getPosition(canvas);
canvas.addEventListener("mousemove",setMousePosition,false); // <-- this
function getPosition(e1) {
var xPosition = 0;
var yPosition = 0;
while (e1) {
xPosition += (e1.offsetLeft - e1.scrollLeft + e1.clientLeft);
yPosition += (e1.offsetTop - e1.scrollTop + e1.clientTop);
e1 = e1.offsetParent;
}
return { x: xPosition, y: yPosition };
}
function setMousePosition(e) {
mouseX = e.clientX - canvasPos.x;
mouseY = e.clientY - canvasPos.y;
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.beginPath();
ctx.arc(mouseX, mouseY, 50, 0, 2 * Math.PI, true);
ctx.fillStyle = "#FF6A6A";
ctx.fill();
ctx.closePath();
}
function getPosition(e1) {
var xPosition=0;
var yPosition=0;
while(e1) {
xPosition+=(e1.offsetLeft-e1.scrollLeft+e1.clientLeft);
yPosition+=(e1.offsetTop-e1.scrollTop+e1.clientTop);
e1=e1.offsetParent;
}
return {
x: xPosition,
y: yPosition
};
}
<canvas id="canvas"></canvas>

Related

Using Canvas to draw multiple polygons but can not get color to be different for polygons

I an issue with the implementation of drawing multiple polygons on a canvas.
I draw the two polygons,
when I move the mouse into the 2nd polygon it turns red and so does the first polygon (the first polygon should be blue). When I move the mouse into the 1st polygon it turns red and so does the 2nd polygon (the 2nd polygon should be blue).
I found the issue with research of each canvas call; adding a ctx.beginPath() fixed the issue. See below:
<canvas id="myCanvas" width=600 height=600 ></canvas>
<script>
canvas = document.getElementById('myCanvas');
ctx = canvas.getContext('2d');
myimage = new Image();
myimage.src = 'https://i.postimg.cc/SNjPPZGJ/farms-map.png';
myimage.onload = draw
const rect = canvas.getBoundingClientRect();
const polypoints1 = [{x: 200, y: 29}, {x: 500, y: 19}, {x: 465, y: 146}, {x: 130, y: 150}];
const polypoints2 = [{x: 200, y: 229}, {x: 500, y: 219}, {x: 465, y: 346}, {x: 130, y: 350}];
var polyColor = [];
var dragPoint = null;
draw();
canvas.addEventListener('mousedown', onMouseDown);
canvas.addEventListener('mousemove', function(evt) {
polyColor[0]="blue";
polyColor[1]="blue";
if (inside({x:evt.clientX - rect.left, y:(evt.clientY + window.scrollY) - rect.top}, polypoints1)){
polyColor[0]="red";
polyColor[1]="blue";}
if (inside({x:evt.clientX - rect.left, y:(evt.clientY + window.scrollY) - rect.top}, polypoints2)){
polyColor[0]="blue";
polyColor[1]="red";}
draw()
}, false);
function inside(p, vs) {
var inside = false;
for (var i = 0, j = vs.length - 1; i < vs.length; j = i++) {
var xi = vs[i].x, yi = vs[i].y;
var xj = vs[j].x, yj = vs[j].y;
var intersect = ((yi > p.y) != (yj > p.y)) && (p.x < (xj - xi) * (p.y - yi) / (yj - yi) + xi);
if (intersect) inside = !inside;
}
return inside;
};
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
if (myimage) {
ctx.drawImage(myimage, 1, 1)
}
drawLines();
polypoints1.forEach(p => drawPoint(p));
polypoints2.forEach(p => drawPoint(p));
}
function drawPoint(p) {
ctx.beginPath();
ctx.globalAlpha = 1
ctx.fillStyle = "black";
ctx.lineWidth = 2;
ctx.arc(p.x, p.y, 5, 0, 2 * Math.PI, false);
ctx.stroke();
ctx.fill();
}
function drawLines() {
ctx.beginPath();
ctx.lineWidth = 2;
polypoints1.forEach(p => ctx.lineTo(p.x, p.y));
ctx.lineTo(polypoints1[0].x, polypoints1[0].y);
ctx.stroke();
if (!dragPoint) {
ctx.globalAlpha = 0.2
ctx.fillStyle = polyColor[0];
ctx.fill();
}
ctx.beginPath();
ctx.lineWidth = 2;
polypoints2.forEach(p => ctx.lineTo(p.x, p.y));
ctx.lineTo(polypoints2[0].x, polypoints2[0].y);
ctx.stroke();
if (!dragPoint) {
ctx.globalAlpha = 0.2
ctx.fillStyle = polyColor[1];
ctx.fill();
}
}
function findDragPoint(x, y) {
for (i = 0; i < polypoints1.length; i++) {
if (hitTest(polypoints1[i], x, y)) return polypoints1[i];
if (hitTest(polypoints2[i], x, y)) return polypoints2[i];
};
return null;
}
function onMouseDown(event) {
dragPoint = findDragPoint(event.clientX - canvas.offsetLeft, event.clientY - canvas.offsetTop + window.scrollY);
if (dragPoint) {
dragPoint.x = event.clientX - canvas.offsetLeft;
dragPoint.y = event.clientY - canvas.offsetTop + window.scrollY;
draw();
canvas.addEventListener("mousemove", onMouseMove);
canvas.addEventListener("mouseup", onMouseUp);
}
}
function onMouseMove(event) {
dragPoint.x = event.clientX - canvas.offsetLeft;
dragPoint.y = event.clientY - canvas.offsetTop+ window.scrollY;
draw();
}
function onMouseUp() {
dragPoint = null;
draw();
canvas.removeEventListener("mousemove", onMouseMove);
canvas.removeEventListener("mouseup", onMouseUp);
}
function hitTest(p, x, y) {
var dx = p.x - x, dy = p.y - y;
return Math.sqrt(dx * dx + dy * dy) <= 10;
}
</script>
I found that you have to use ctx.beginPath() before you start to set up the second polygon. This seems to have addressed the issue.

Determine the distance between a straight line and a curve line drawn in a HTML canvas

I have a program in HTML, CSS and JavaScript where one can draw a from an initial point (Mousedown event )curved line(Mousemove event) and a straight line when the mouse click is lifted up(MouseUp event).
Now my problem is finding the distance of the curve line and as well as the straight line in two different labels.
My code goes below
var canvas = document.querySelector('#paint');
var ctx = canvas.getContext('2d');
var sketch = document.querySelector('#sketch');
var sketch_style = getComputedStyle(sketch);
canvas.width = parseInt(sketch_style.getPropertyValue('width'));
canvas.height = parseInt(sketch_style.getPropertyValue('height'));
var mouse = {
x: 0,
y: 0
};
var last_mouse = {
x: 0,
y: 0
};
/* Mouse Capturing Work */
canvas.addEventListener('mousemove', function(e) {
last_mouse.x = mouse.x;
last_mouse.y = mouse.y;
mouse.x = e.pageX - this.offsetLeft;
mouse.y = e.pageY - this.offsetTop;
}, false);
/* Drawing on Paint App */
ctx.lineWidth = 5;
ctx.lineJoin = 'round';
ctx.lineCap = 'round';
ctx.strokeStyle = 'black';
canvas.addEventListener('mousedown', function(e) {
initialPoint = {
x: mouse.x,
y: mouse.y
}
canvas.addEventListener('mousemove', onPaint, false);
}, false);
canvas.addEventListener('mouseup', function() {
drawStraightLine()
canvas.removeEventListener('mousemove', onPaint, false);
}, false);
var onPaint = function() {
ctx.beginPath();
ctx.moveTo(last_mouse.x, last_mouse.y);
ctx.lineTo(mouse.x, mouse.y);
ctx.strokeStyle = "#000000";
ctx.closePath();
ctx.stroke();
};
let initialPoint
const drawStraightLine = function() {
ctx.beginPath();
ctx.moveTo(initialPoint.x, initialPoint.y);
ctx.lineTo(mouse.x, mouse.y);
ctx.strokeStyle = "#FF000077";
ctx.stroke();
}
html,
body {
width: 80%;
height: 50%;
}
#sketch {
border: 10px solid gray;
height: 100%;
}
<div id="sketch">
<canvas id="paint"></canvas>
<script src="1.js"></script>
</div>
<label id="StraightLineDistance"></label>
<label id="CurvedLineDistance"></label>
To find the length of a line you use Pythagoras
Eg the distance between two points A, B
function distanceBetween(A, B) {
return ((B.x - A.x) ** 2 + (B.y - A.y) ** 2) ** 0.5;
}
Or
function distanceBetween(A, B) {
const dx = B.x - A.x;
const dy = B.y - A.y;
return Math.sqrt(dx * dx + dy * dy);
}
Or
function distanceBetween(A, B) {
return Math.hypot(B.x - A.x, B.y - A.y);
}
To measure the drawn path you will need to accumulate the length each sub path (line) to get a total.
Example
The example accumulates the length as it is drawn. When the mouse down event happens the accumulated length is zeroed.
const canvas = document.querySelector('#paint');
const ctx = canvas.getContext('2d');
const sketch = document.querySelector('#sketch');
const sketch_style = getComputedStyle(sketch);
canvas.width = parseInt(sketch_style.getPropertyValue('width'));
canvas.height = parseInt(sketch_style.getPropertyValue('height'));
var pathLength = 0;
var distance = 0;
const mouse = {x: 0, y: 0};
const last_mouse = {x: 0, y: 0};
const initialPoint = {x: 0, y: 0};
function distanceBetween(A, B) {
const dx = B.x - A.x;
const dy = B.y - A.y;
return (dx * dx + dy * dy) ** 0.5;
}
/* Drawing on Paint App */
ctx.lineWidth = 5;
ctx.lineJoin = 'round';
ctx.lineCap = 'round';
ctx.strokeStyle = 'black';
canvas.addEventListener('mousedown', function(e) {
initialPoint.x = mouse.x = e.pageX - this.offsetLeft;
initialPoint.y = mouse.y = e.pageY - this.offsetTop;
pathLength = 0;
canvas.addEventListener('mousemove', onPaint);
}, false);
canvas.addEventListener('mouseup', function() {
drawStraightLine()
canvas.removeEventListener('mousemove', onPaint);
}, false);
function displayLengths() {
StraightLineDistance.textContent = "Distance: " + distance.toFixed(0) + "px";
CurvedLineDistance.textContent = "Traveled: " + pathLength.toFixed(0) + "px";
}
function onPaint(e) {
last_mouse.x = mouse.x;
last_mouse.y = mouse.y;
mouse.x = e.pageX - this.offsetLeft;
mouse.y = e.pageY - this.offsetTop;
ctx.strokeStyle = "#000000";
ctx.beginPath();
ctx.lineTo(last_mouse.x, last_mouse.y);
ctx.lineTo(mouse.x, mouse.y);
ctx.stroke();
pathLength += distanceBetween(last_mouse, mouse);
distance = distanceBetween(initialPoint, mouse);
displayLengths();
};
function drawStraightLine() {
ctx.strokeStyle = "#FF000077";
ctx.beginPath();
ctx.lineTo(initialPoint.x, initialPoint.y);
ctx.lineTo(mouse.x, mouse.y);
ctx.stroke();
distance = distanceBetween(initialPoint, mouse);
displayLengths();
}
html,
body {
width: 80%;
height: 50%;
}
#sketch {
border: 10px solid gray;
height: 100%;
}
<div id="sketch">
<canvas id="paint"></canvas>
<script src="1.js"></script>
</div>
<label id="StraightLineDistance"></label>
<label id="CurvedLineDistance"></label>
The JavaScript file
const canvas = document.querySelector('#paint');
const ctx = canvas.getContext('2d');
const sketch = document.querySelector('#sketch');
const sketch_style = getComputedStyle(sketch);
canvas.width = parseInt(sketch_style.getPropertyValue('width'));
canvas.height = parseInt(sketch_style.getPropertyValue('height'));
var pathLength = 0;
var distance = 0;
const mouse = {x: 0, y: 0};
const last_mouse = {x: 0, y: 0};
const initialPoint = {x: 0, y: 0};
function distanceBetween(A, B) {
const dx = B.x - A.x;
const dy = B.y - A.y;
return (dx * dx + dy * dy) ** 0.5;
}
/* Drawing on Paint App */
ctx.lineWidth = 5;
ctx.lineJoin = 'round';
ctx.lineCap = 'round';
ctx.strokeStyle = 'black';
canvas.addEventListener('mousedown', function(e) {
initialPoint.x = mouse.x = e.pageX - this.offsetLeft;
initialPoint.y = mouse.y = e.pageY - this.offsetTop;
pathLength = 0;
canvas.addEventListener('mousemove', onPaint);
}, false);
canvas.addEventListener('mouseup', function() {
drawStraightLine()
canvas.removeEventListener('mousemove', onPaint);
}, false);
function displayLengths() {
StraightLineDistance.textContent = "Distance: " + distance.toFixed(0) + "px";
CurvedLineDistance.textContent = "Traveled: " + pathLength.toFixed(0) + "px";
}
function onPaint(e) {
last_mouse.x = mouse.x;
last_mouse.y = mouse.y;
mouse.x = e.pageX - this.offsetLeft;
mouse.y = e.pageY - this.offsetTop;
ctx.strokeStyle = "#000000";
ctx.beginPath();
ctx.lineTo(last_mouse.x, last_mouse.y);
ctx.lineTo(mouse.x, mouse.y);
ctx.stroke();
pathLength += distanceBetween(last_mouse, mouse);
distance = distanceBetween(initialPoint, mouse);
displayLengths();
};
function drawStraightLine() {
ctx.strokeStyle = "#FF000077";
ctx.beginPath();
ctx.lineTo(initialPoint.x, initialPoint.y);
ctx.lineTo(mouse.x, mouse.y);
ctx.stroke();
distance = distanceBetween(initialPoint, mouse);
displayLengths();
}
The HTML file
<link rel="stylesheet" href="1.css"/>
</head>
<body>
<div id="sketch">
<canvas id="paint"></canvas>
<script src="1.js"></script>
</div>
<label id="StraightLineDistance"></label><br/>
<label id="CurvedLineDistance"></label><br/>
<label id="Index"></label>
</body>
</html>
My new doubt is how can I show the realtime value of ratio of (distance/pathLength) in the label id="Index"
I have tried using Index.textContent = (distance/pathLength).toFixed(0); but that shows 1 and its constant in the output.
I would be pleased if I am helped with this

Drawing multiple rectangles on canvas without clearing the back image

I am trying to draw multiple rectangles on canvas. I am able to do it except its not clearing rectangles as the mouse moves.
And when i try to clear rectangle using clearRect then the back image on canvas is also gets cleared. So I have commented out //ctx.clearRect(0, 0, canvas.width, canvas.height); in the code below
I have gone through several SO posts with similar questions but doesn't seems work
$(function(){
var canvas = document.getElementById('myCanvas');
if (canvas.getContext){
var ctx = canvas.getContext('2d');
ctx.fillText("Sample String", 20, 50);
}
var ctx = canvas.getContext('2d');
//Variables
var canvasx = $(canvas).offset().left;
var canvasy = $(canvas).offset().top;
var last_mousex = last_mousey = 0;
var mousex = mousey = 0;
var mousedown = false;
//Mousedown
$(canvas).on('mousedown', function (e) {
last_mousex = parseInt(e.clientX - canvasx);
last_mousey = parseInt(e.clientY - canvasy);
mousedown = true;
});
//Mouseup
$(canvas).on('mouseup', function (e) {
mousedown = false;
});
//Mousemove
$(canvas).on('mousemove', function (e) {
mousex = parseInt(e.clientX - canvasx);
mousey = parseInt(e.clientY - canvasy);
if (mousedown) {
//ctx.clearRect(0, 0, canvas.width, canvas.height);
var width = mousex - last_mousex;
var height = mousey - last_mousey;
ctx.beginPath();
ctx.rect(last_mousex, last_mousey, width, height);
ctx.strokeStyle = 'black';
ctx.lineWidth = 1;
ctx.stroke();
}
//Output
$('#results').html('current: ' + mousex + ', ' + mousey + '<br/>last: ' + last_mousex + ', ' + last_mousey + '<br/>mousedown: ' + mousedown);
});
})
canvas { border: 1px solid black; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h3>
Use mouse to draw multiple rectangles with in the canvas
</h3>
<canvas id="myCanvas"></canvas>
<div id="results">
</div>
your mistake was you cleared all the canvas:
ctx.clearRect(0, 0, canvas.width, canvas.height);
instead of clearing just the area you drew before:
ctx.clearRect(prev_x-1, prev_y-1, prev_w+2, prev_h+2);
I wrote the basic idea here, but you need to add some code to clear the area depends on the direction the mouse was, and moving to (try to move your mouse to each of the corners and see what happens).
$("#clear").click(function(){
var canvas = document.getElementById('myCanvas');
var ctx = canvas.getContext('2d');
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.fillText("Sample String", 20, 50);
});
$(function(){
var canvas = document.getElementById('myCanvas');
if (canvas.getContext){
var ctx = canvas.getContext('2d');
ctx.fillText("Sample String", 20, 50);
}
var ctx = canvas.getContext('2d');
//Variables
var canvasx = $(canvas).offset().left;
var canvasy = $(canvas).offset().top;
var last_mousex = last_mousey = w = h = 0;
var prev_x = prev_y = prev_w = prev_h = 0;
var mousex = mousey = 0;
var mousedown = false;
//Mousedown
$(canvas).on('mousedown', function (e) {
last_mousex = parseInt(e.clientX - canvasx);
last_mousey = parseInt(e.clientY - canvasy);
mousedown = true;
});
//Mouseup
$(canvas).on('mouseup', function (e) {
w = h = 0;
mousedown = false;
});
//Mousemove
$(canvas).on('mousemove', function (e) {
mousex = parseInt(e.clientX - canvasx);
mousey = parseInt(e.clientY - canvasy);
if (mousedown) {
prev_x = last_mousex;
prev_y = last_mousey;
prev_w = w;
prev_h = h;
ctx.clearRect(prev_x-1, prev_y-1, prev_w+2, prev_h+2);
w = mousex - last_mousex;
h = mousey - last_mousey;
ctx.beginPath();
ctx.rect(last_mousex, last_mousey, w, h);
ctx.strokeStyle = 'black';
ctx.lineWidth = 1;
ctx.stroke();
}
//Output
$('#results').html('current: ' + mousex + ', ' + mousey + '<br/>last: ' + last_mousex + ', ' + last_mousey + '<br/>mousedown: ' + mousedown);
});
})
canvas { border: 1px solid black; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h3>
Use mouse to draw multiple rectangles with in the canvas
</h3>
<button id="clear">clear</button>
<br />
<canvas id="myCanvas"></canvas>
<div id="results">
</div>
I think you can come to another approach
By using mousedown event only then save all rectangle to an array variable
Then you can clear and redraw the whole canvas with the saved variable
var shapes = [];
canva.addEventListener('mousedown', mouseDownListener);
class Rectangle() {
public ctx, x, y, w, h;
public Rectangle(ctx, x, y, w, h) {
this.ctx = ctx;
this.x = x;
this.y = y;
this.w = w;
this.h = h;
}
public draw() {
// draw using ctx here
}
}
function mouseDownListener() {
// create rectable
var rectangle = new Rectangle(ctx, x, y, width, height);
// save rectangle to an array
shapes.push(rectangle);
// redraw canvas
redraw();
}
function redraw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
// draw all rectangle
shapes.forEach(function(shape) {
// draw shape
shape.draw();
})
}

HTML5 Canvas Javascript how to make smooth brush

Hello i need make smooth brush likes this:
I try to create it, i make circle and fill it, but result not successful:
Can be seen circles.. this is not smooth like first example
my example code:
function distanceBetween(point1, point2) {
return Math.sqrt(Math.pow(point2.x - point1.x, 2) + Math.pow(point2.y - point1.y, 2));
}
function angleBetween(point1, point2) {
return Math.atan2( point2.x - point1.x, point2.y - point1.y );
}
var el = document.getElementById('c');
var ctx = el.getContext('2d');
//ctx.fillStyle = "rgba('255, 0, 0, 0.1')";
ctx.fillStyle = "red";
ctx.strokeStyle = "red";
ctx.globalAlpha = "0.05";
ctx.lineWidth = 0;
ctx.globalCompositeOperation = "source-over";
var isDrawing, lastPoint;
el.onmousedown = function(e) {
isDrawing = true;
lastPoint = { x: e.clientX, y: e.clientY };
};
el.onmousemove = function(e) {
if (!isDrawing) return;
var currentPoint = { x: e.clientX, y: e.clientY };
var dist = distanceBetween(lastPoint, currentPoint);
var angle = angleBetween(lastPoint, currentPoint);
for (var i = 0; i < dist; i+=5) {
x = lastPoint.x + (Math.sin(angle) * i) - 25;
y = lastPoint.y + (Math.cos(angle) * i) - 25;
ctx.beginPath();
ctx.arc(x+10, y+10, 20, false, Math.PI * 2, false);
ctx.closePath();
ctx.fill();
ctx.stroke();
}
lastPoint = currentPoint;
};
el.onmouseup = function() {
isDrawing = false;
};
function clearit() {
ctx.clearRect(0,0, 1000, 1000);
}
canvas { border: 1px solid #ccc }
<canvas id="c" width="500" height="300"></canvas>
<input type="button" id="clear-btn" value="Clear it" onclick="clearit()">
http://codepen.io/anon/pen/NPjwry
Try with a smaller globalAlpha and decrease the stepping (so you draw more circles)
function distanceBetween(point1, point2) {
return Math.sqrt(Math.pow(point2.x - point1.x, 2) + Math.pow(point2.y - point1.y, 2));
}
function angleBetween(point1, point2) {
return Math.atan2( point2.x - point1.x, point2.y - point1.y );
}
var el = document.getElementById('c');
var ctx = el.getContext('2d');
//ctx.fillStyle = "rgba('255, 0, 0, 0.1')";
ctx.fillStyle = "red";
ctx.strokeStyle = "red";
ctx.globalAlpha = "0.01";
ctx.lineWidth = 0;
ctx.globalCompositeOperation = "source-over";
var isDrawing, lastPoint;
el.onmousedown = function(e) {
isDrawing = true;
lastPoint = { x: e.clientX, y: e.clientY };
};
el.onmousemove = function(e) {
if (!isDrawing) return;
var currentPoint = { x: e.clientX, y: e.clientY };
var dist = distanceBetween(lastPoint, currentPoint);
var angle = angleBetween(lastPoint, currentPoint);
for (var i = 0; i < dist; i+=3) {
x = lastPoint.x + (Math.sin(angle) * i) - 25;
y = lastPoint.y + (Math.cos(angle) * i) - 25;
ctx.beginPath();
ctx.arc(x+10, y+10, 20, false, Math.PI * 2, false);
ctx.closePath();
ctx.fill();
ctx.stroke();
}
lastPoint = currentPoint;
};
el.onmouseup = function() {
isDrawing = false;
};
function clearit() {
ctx.clearRect(0,0, 1000, 1000);
}
canvas { border: 1px solid #ccc }
<canvas id="c" width="500" height="300"></canvas>
<input type="button" id="clear-btn" value="Clear it" onclick="clearit()">
Updated codepen: http://codepen.io/gpetrioli/pen/ramqBz
There is more simple solution: just set width of line to 25px
let ctx = this.d.transparentUpdateImage.getContext('2d');
if (!this.lastPos) {
this.lastPos = {x: x, y: y};
return
}
ctx.beginPath();
ctx.moveTo(this.lastPos.x, this.lastPos.y);
ctx.lineCap = 'round';
ctx.lineJoin = 'round';
ctx.strokeStyle = 'red';
ctx.lineWidth = 25;
ctx.lineTo(x, y);
ctx.stroke();
ctx.closePath();
this.lastPos = {x: x, y: y};

Adding html content on a moving element in Canvas

How I can add Html content on a moving element in the Canvas, like this one
http://www.html5canvastutorials.com/labs/html5-canvas-harmonic-oscillator/
where I need to display my link or button on the moving block attached to the spring. Generally for static canvas elements we can use Z-index or overlapping techniques, but these don't work in this case.
Any solutions ?
Check if the following script works:
<script src="http://www.html5canvastutorials.com/libraries/kinetic2d-v1.0.3.js">
</script>
<script>
var button = {
x: 0,
y: 0,
size: 16,
width: 0,
height: 0,
padding: 4,
hover: false,
text: "Click Me",
onclick: function (e) {
// put your event handler code here
}
};
function drawSpring(canvas, context){
context.beginPath();
context.moveTo(0, 0);
for (var y = 0; y < 200; y++) {
// Sine wave equation
var x = 30 * Math.sin(y / 9.05);
context.lineTo(x, y);
}
}
function drawWeight(canvas, context, y){
var size = 100;
context.save();
context.fillStyle = "red";
context.fillRect(-size / 2, 0, size, size);
context.restore();
canvas.fillText(button.text, 0, 0);
button.x = ((canvas.width - button.width) / 2) - button.padding;
button.y = (y + (size - button.height) / 2) - button.padding;
}
window.onload = function(){
var kin = new Kinetic_2d("myCanvas");
var canvas = kin.getCanvas();
var context = kin.getContext();
context.font = button.size + "px Verdana";
context.textAlign = "center";
context.textBaseline = "top";
button.width = 2 * button.padding + context.measureText(button.text);
button.height = 2 * button.padding + button.size;
var theta = 0;
var curleft = 0;
var curtop = 0;
var obj = canvas;
do {
curleft += object.offsetLeft;
curtop += object.offsetTop;
} while (obj = obj.offsetParent);
canvas.addEventListener("mousemove", function (e) {
context.beginPath();
context.rect(button.x, button.y, button.width, button.height);
button.hover = context.isPointInPath(e.pageX - curleft, e.pageY - curtop);
}, false);
canvas.addEventListener("click", function (e) {
if (button.hover) button.onclick(e);
}, false);
kin.setDrawStage(function(){
theta += this.getTimeInterval() / 400;
var scale = 0.8 * (Math.sin(theta) + 1.3);
this.clear();
context.save();
context.translate(canvas.width / 2, 0);
context.save();
context.scale(1, scale);
drawSpring(canvas, context);
context.restore();
context.lineWidth = 6;
context.strokeStyle = "#0096FF"; // blue-ish color
context.stroke();
context.translate(0, 200 * scale);
drawWeight(canvas, context, 200 * scale);
context.restore();
});
kin.startAnimation();
};
</script>

Categories

Resources