I'm trying to create a circle navigation button to follow mouse movement when the cursor is inside a certain box.
var cer = document.getElementById('cerchio');
var pro = document.getElementById('prova');
pro.addEventListener("mouseover", function() {
var e = window.event;
var x = e.clientX;
var y = e.clientY;
cer.style.top = y + "px";
cer.style.left = x + "px";
cer.style.transition = "2s";
});
pro.addEventListener("mouseout", function() {
cer.style.top = "15px";
cer.style.left = "15px";
});
#prova {
width: 200px;
height: 200px;
border: 1px solid black;
}
#cerchio {
width: 90px;
height: 90px;
border: 1px solid red;
border-radius: 90px;
position: absolute;
left: 15px;
top: 15px;
}
#innercircle {
width: 120px;
height: 120px;
position: relative;
left: 40px;
top: 30px;
border: 1px solid red;
}
<div id="prova">
<div id="innercircle">
<div id="cerchio"></div>
</div>
</div>
so it actually follows the first position of the mouse inside the black bordered box, i want it to update the cursor positioning every time and follow it, also i don't want the red circle to go out the red box, any suggestion? please javascript only not jquery, thanks!
The main problem is your usage of window.event and wrong event handlers.
Here's a solution that uses standard event handling:
var cer = document.getElementById('cerchio');
var pro = document.getElementById('prova');
var proR = pro.getBoundingClientRect();
var cirR = cer.getBoundingClientRect();
// radii
var rW = (cirR.right - cirR.left) / 2;
var rH = (cirR.bottom - cirR.top) / 2;
// page coords of center
var oX = (proR.right + proR.left) / 2;
var oY = (proR.bottom + proR.top) / 2;
var x, y;
// max movement
var max = 15;
function setPos(x, y) {
cer.style.left = (x + oX - rW) + "px";
cer.style.top = (y + oY - rH) + "px";
}
pro.addEventListener("mouseleave", function() {
setPos(0, 0);
});
pro.addEventListener("mousemove", function(e) {
// 0,0 is at center
x = e.clientX - oX;
y = e.clientY - oY;
// limit to max
if (x < -max) x = -max;
if (x > max) x = max;
if (y < -max) y = -max;
if (y > max) y = max;
// set circle position
setPos(x, y);
});
setPos(0, 0);
#prova {
display: inline-block;
border: 1px solid black;
padding: 40px;
}
#innercircle {
width: 120px;
height: 120px;
border: 1px solid red;
}
#cerchio {
width: 90px;
height: 90px;
border: 1px solid red;
border-radius: 50%;
transition: .5s;
position: absolute;
pointer-events: none;
}
#prova,
#innercircle,
#cerchio {
box-sizing: border-box;
}
<div id="prova">
<div id="innercircle">
<div id="cerchio"></div>
</div>
</div>
I've also changed the calculation to
determine the x,y values such that the center of the area is (0, 0)
limit the values to a set boundary
add back the offset to position the circle
Your main problem is that you're using 'mouseover'. This event only activates when the mouse enters the element. This way, if works the first time you move over the rectangle, or when you move between the black and red rectangles.
If you use 'mousemove', it works right.
var cer = document.getElementById('cerchio');
var pro = document.getElementById('prova');
pro.addEventListener("mousemove", function() {
var e = window.event;
var x = e.clientX;
var y = e.clientY;
cer.style.top = y + "px";
cer.style.left = x + "px";
cer.style.transition = "2s";
});
pro.addEventListener("mouseout", function() {
cer.style.top = "15px";
cer.style.left = "15px";
});
#prova {
width: 200px;
height: 200px;
border: 1px solid black;
}
#cerchio {
width: 90px;
height: 90px;
border: 1px solid red;
border-radius: 90px;
position: absolute;
left: 15px;
top: 15px;
}
#innercircle {
width: 120px;
height: 120px;
position: relative;
left: 40px;
top: 30px;
border: 1px solid red;
}
<div id="prova">
<div id="innercircle">
<div id="cerchio"></div>
</div>
</div>
"mousemove" is the event you want to track for this as you want the position of the mouse as it moves inside the element. You should also pass the event as a callback to the event handler
I also fixed the positioning using the getBoundingClientRect() method.
var cer = document.getElementById('cerchio');
var pro = document.getElementById('prova');
var innerC = document.getElementById('innercircle');
innerC.addEventListener("mousemove", function(e) {
var square = this.getBoundingClientRect();
var squareX = square.x;
var squareY = square.y;
var squareWidth = square.width;
var squareHeight = square.height;
var mouseX = e.clientX;
var mouseY= e.clientY;
var x = e.clientX;
var y = e.clientY;
cer.style.top = (-squareY + mouseY - (squareHeight / 2 - 15)) + "px";
cer.style.left = (-squareX + mouseX - (squareWidth / 2 - 15)) + "px";
cer.style.transition = "2s";
});
innerC.addEventListener("mouseout", function() {
cer.style.top = "15px";
cer.style.left = "15px";
});
#prova {
width: 200px;
height: 200px;
border: 1px solid black;
}
#cerchio {
width: 90px;
height: 90px;
border: 1px solid red;
border-radius: 90px;
position: absolute;
z-index: -1;
left: 15px;
top: 15px;
}
#innercircle {
width: 120px;
height: 120px;
position: relative;
z-index: 2;
left: 40px;
top: 30px;
border: 1px solid red;
}
<div id="prova">
<div id="innercircle">
<div id="cerchio"></div>
Related
I have two circles that intersect and I want to make the intersecting area have a color, even when the two circles are transparent. I thought I could find some way to do this with css mix-blend-mode property but I have had no success with it.
Of course, I could make the circles have color and decrease their opacity, but I want them to be either white or transparent, where only the overlapped area gets background color.
I want the intersecting area to be able to change dynamically because one circle will follow the mouse.
Here is the codepen for that.
I'm not sure where to start on this, if css has some technique or if it will have to be done with jquery.
$(document).mousemove(function(e) {
$('.cursor').eq(0).css({
left: e.pageX - 25,
top: e.pageY - 20
});
// circles
var c1 = $('.cursor');
var c2 = $('.circle');
// radius
var d1 = c1.outerWidth(true)/2;
var d2 = c2.outerWidth(true)/2;
// centers of first circle
var x1 = c1.offset().left + c1.width()/2;
var y1 = c1.offset().top + c1.height()/2;
// centers of second circle
var x2 = c2.offset().left + c2.width()/2;
var y2 = c2.offset().top + c2.height()/2;
var i1 = c2.find('.inter1');
var i2 = c2.find('.inter2');
var o = c1.find('.overlap');
function calc() {
var a = d2;
var b = d1;
var c = Math.sqrt((x1-x2)*(x1-x2)+(y1-y2)*(y1-y2));
var d = (b*b+c*c-a*a)/(2*c);
var h = Math.sqrt((b*b) - (d*d));
if (d < 0 || $.isNumeric(h)) {
c2.css('border-color', 'red');
} else {
c2.css('border-color', 'black');
}
var x3 = (x2-x1)*d/c + (y2-y1)*h/c + x1;
var y3 = (y2-y1)*d/c - (x2-x1)*h/c + y1;
var x4 = (x2-x1)*d/c - (y2-y1)*h/c + x1;
var y4 = (y2-y1)*d/c + (x2-x1)*h/c + y1;
if ($.isNumeric(h)) {
i1.show();
i2.show();
} else {
i1.hide();
i2.hide();
}
i1.offset({ top: y3-5, left: x3-5});
i2.offset({ top: y4-5, left: x4-5});
} calc();
});
body {
background: #fff;
}
.overlap {
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
background: rgba(0, 0, 0, 0.5);
}
.cursor {
height: 50px;
width: 50px;
border-radius: 50%;
position: absolute;
pointer-events: none;
z-index: 999;
border: 1px solid black;
outline: 1px solid #c9d3ff;
overflow: none;
}
.circle {
border-radius: 50%;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
width: 200px;
height: 200px;
border: 1px solid black;
outline: 1px solid #c9d3ff;
}
.circle::after,
.cursor::after {
display: block;
content: '';
height: 1px;
background: #c9d3ff;
position: absolute;
top: 50%;
left: 0;
right: 0;
}
.circle::before,
.cursor::before {
display: block;
content: '';
width: 1px;
background: #c9d3ff;
position: absolute;
left: 50%;
top: 0;
bottom: 0;
}
.inter {
width: 10px;
height: 10px;
background: black;
border-radius: 50%;
position: absolute;
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="cursor">
</div>
<div class="circle">
<div class="inter1 inter"></div>
<div class="inter2 inter"></div>
<div>
One way you can approach this is by adding a "inner-cursor" circle inside the main circle. Based on mouse movement it will move with the main cursor given the illusion of overlap.
In this case, the background color of the intersecting circles will not matter. Also, you do not have to worry about mix-blend-mode since the inner cursor has a background color and is hidden. It is only viewed if the mouse hovers over the main circle.
See this example:
$(document).mousemove(function(e) {
// elements
let cursor = $('.cursor');
let innerCursor = $('.inner-cursor');
let c2 = $('.circle');
let pos = {
left: e.pageX - 25,
top: e.pageY - 20
};
cursor.css(pos);
innerCursor.css({
left: pos.left - c2.offset().left,
top: pos.top - c2.offset().top
});
// circles
// radius
var d1 = cursor.outerWidth(true) / 2;
var d2 = c2.outerWidth(true) / 2;
// centers of first circle
var x1 = cursor.offset().left + cursor.width() / 2;
var y1 = cursor.offset().top + cursor.height() / 2;
// centers of second circle
var x2 = c2.offset().left + c2.width() / 2;
var y2 = c2.offset().top + c2.height() / 2;
var i1 = c2.find('.inter1');
var i2 = c2.find('.inter2');
var o = cursor.find('.overlap');
function calc() {
var a = d2;
var b = d1;
var c = Math.sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2));
var d = (b * b + c * c - a * a) / (2 * c);
var h = Math.sqrt((b * b) - (d * d));
// console.log(a, b, c, d, h);
if (d < 0 || $.isNumeric(h)) {
c2.css('border-color', 'red');
} else {
c2.css('border-color', 'black');
}
var x3 = (x2 - x1) * d / c + (y2 - y1) * h / c + x1;
var y3 = (y2 - y1) * d / c - (x2 - x1) * h / c + y1;
var x4 = (x2 - x1) * d / c - (y2 - y1) * h / c + x1;
var y4 = (y2 - y1) * d / c + (x2 - x1) * h / c + y1;
if ($.isNumeric(h)) {
i1.show();
i2.show();
} else {
i1.hide();
i2.hide();
}
i1.offset({
top: y3 - 5,
left: x3 - 5
});
i2.offset({
top: y4 - 5,
left: x4 - 5
});
}
calc();
});
body {
background: #fff;
}
.clip {
display: inline-block;
background: blue;
height: 50px;
width: 50px;
border-radius: 50%;
clip-path: ellipse(50px 50px at 50% 0%);
position: absolute;
left: 750px;
top: 40px;
}
.cursor {
left: 750px;
top: 40px;
}
.cursor {
height: 50px;
width: 50px;
border-radius: 50%;
position: absolute;
pointer-events: none;
z-index: 999;
border: 1px solid black;
outline: 1px solid #c9d3ff;
overflow: none;
mix-blend-mode: multiply;
background: rgba(100, 100, 100, 0.1);
}
.circle {
background: rgba(100, 100, 100, 0.1);
border-radius: 50%;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
width: 200px;
height: 200px;
border: 1px solid black;
outline: 1px solid #c9d3ff;
overflow: hidden;
}
.circle::after,
.cursor::after {
display: block;
content: '';
height: 1px;
background: #c9d3ff;
position: absolute;
top: 50%;
left: 0;
right: 0;
}
.circle::before,
.cursor::before {
display: block;
content: '';
width: 1px;
background: #c9d3ff;
position: absolute;
left: 50%;
top: 0;
bottom: 0;
}
.inter {
width: 10px;
height: 10px;
background: black;
border-radius: 50%;
position: absolute;
display: none;
}
.inner-cursor {
height: 50px;
width: 50px;
border-radius: 50%;
position: absolute;
pointer-events: none;
background: green;
left: 50%;
top: 50%;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="cursor">
</div>
<span class="clip"></span>
<div class="circle">
<div class='inner-cursor'></div>
<div class="inter1 inter"></div>
<div class="inter2 inter"></div>
</div>
On easy idea using only CSS is to consider a radial-gradient as background using background-attachement:fixed. You apply this background to the cursor element and you make its dimension/position the same as the fixed element.
All you need to add in your code is:
background:radial-gradient(circle,blue 100px,transparent 100px) fixed no-repeat
I have also optimized the code to remove the line you draw with pseudo element to consider linear-gradient
$(document).mousemove(function(e) {
$('.cursor').eq(0).css({
left: e.pageX - 25,
top: e.pageY - 20
});
// circles
var c1 = $('.cursor');
var c2 = $('.circle');
// radius
var d1 = c1.outerWidth(true)/2;
var d2 = c2.outerWidth(true)/2;
// centers of first circle
var x1 = c1.offset().left + c1.width()/2;
var y1 = c1.offset().top + c1.height()/2;
// centers of second circle
var x2 = c2.offset().left + c2.width()/2;
var y2 = c2.offset().top + c2.height()/2;
var i1 = c2.find('.inter1');
var i2 = c2.find('.inter2');
var o = c1.find('.overlap');
function calc() {
var a = d2;
var b = d1;
var c = Math.sqrt((x1-x2)*(x1-x2)+(y1-y2)*(y1-y2));
var d = (b*b+c*c-a*a)/(2*c);
var h = Math.sqrt((b*b) - (d*d));
if (d < 0 || $.isNumeric(h)) {
c2.css('border-color', 'red');
} else {
c2.css('border-color', 'black');
}
var x3 = (x2-x1)*d/c + (y2-y1)*h/c + x1;
var y3 = (y2-y1)*d/c - (x2-x1)*h/c + y1;
var x4 = (x2-x1)*d/c - (y2-y1)*h/c + x1;
var y4 = (y2-y1)*d/c + (x2-x1)*h/c + y1;
if ($.isNumeric(h)) {
i1.show();
i2.show();
} else {
i1.hide();
i2.hide();
}
i1.offset({ top: y3-5, left: x3-5});
i2.offset({ top: y4-5, left: x4-5});
} calc();
});
body {
background: #fff;
margin:0;
}
*{
box-sizing:border-box;
}
.cursor {
height: 50px;
width: 50px;
border-radius: 50%;
position: absolute;
pointer-events: none;
z-index: 999;
border: 1px solid black;
outline: 1px solid #c9d3ff;
background:
linear-gradient(#c9d3ff,#c9d3ff) center/100% 1px,
linear-gradient(#c9d3ff,#c9d3ff) center/1px 100%,
radial-gradient(circle,blue 100px,transparent 101px) fixed,
yellow;
background-repeat:no-repeat;
}
.circle {
border-radius: 50%;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
width: 200px;
height: 200px;
border: 1px solid black;
outline: 1px solid #c9d3ff;
background:
linear-gradient(#c9d3ff,#c9d3ff) center/100% 1px,
linear-gradient(#c9d3ff,#c9d3ff) center/1px 100%,
#f2f2f2;
background-repeat:no-repeat;
}
.inter {
width: 10px;
height: 10px;
background: black;
border-radius: 50%;
position: absolute;
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="cursor">
</div>
<div class="circle">
<div class="inter1 inter"></div>
<div class="inter2 inter"></div>
<div>
And if the circle is not in the middle you simply adjust the position.
$(document).mousemove(function(e) {
$('.cursor').eq(0).css({
left: e.pageX - 25,
top: e.pageY - 20
});
// circles
var c1 = $('.cursor');
var c2 = $('.circle');
// radius
var d1 = c1.outerWidth(true)/2;
var d2 = c2.outerWidth(true)/2;
// centers of first circle
var x1 = c1.offset().left + c1.width()/2;
var y1 = c1.offset().top + c1.height()/2;
// centers of second circle
var x2 = c2.offset().left + c2.width()/2;
var y2 = c2.offset().top + c2.height()/2;
var i1 = c2.find('.inter1');
var i2 = c2.find('.inter2');
var o = c1.find('.overlap');
function calc() {
var a = d2;
var b = d1;
var c = Math.sqrt((x1-x2)*(x1-x2)+(y1-y2)*(y1-y2));
var d = (b*b+c*c-a*a)/(2*c);
var h = Math.sqrt((b*b) - (d*d));
if (d < 0 || $.isNumeric(h)) {
c2.css('border-color', 'red');
} else {
c2.css('border-color', 'black');
}
var x3 = (x2-x1)*d/c + (y2-y1)*h/c + x1;
var y3 = (y2-y1)*d/c - (x2-x1)*h/c + y1;
var x4 = (x2-x1)*d/c - (y2-y1)*h/c + x1;
var y4 = (y2-y1)*d/c + (x2-x1)*h/c + y1;
if ($.isNumeric(h)) {
i1.show();
i2.show();
} else {
i1.hide();
i2.hide();
}
i1.offset({ top: y3-5, left: x3-5});
i2.offset({ top: y4-5, left: x4-5});
} calc();
});
body {
background: #fff;
margin:0;
}
*{
box-sizing:border-box;
}
.cursor {
height: 50px;
width: 50px;
border-radius: 50%;
position: absolute;
pointer-events: none;
z-index: 999;
border: 1px solid black;
outline: 1px solid #c9d3ff;
background:
linear-gradient(#c9d3ff,#c9d3ff) center/100% 1px,
linear-gradient(#c9d3ff,#c9d3ff) center/1px 100%,
radial-gradient(circle at 20% 50%,blue 100px,transparent 101px) fixed
yellow;
background-repeat:no-repeat;
}
.circle {
border-radius: 50%;
position: absolute;
top: 50%;
left: 20%;
transform: translate(-50%, -50%);
width: 200px;
height: 200px;
border: 1px solid black;
outline: 1px solid #c9d3ff;
background:
linear-gradient(#c9d3ff,#c9d3ff) center/100% 1px,
linear-gradient(#c9d3ff,#c9d3ff) center/1px 100%,
#f2f2f2;
background-repeat:no-repeat;
}
.inter {
width: 10px;
height: 10px;
background: black;
border-radius: 50%;
position: absolute;
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="cursor">
</div>
<div class="circle">
<div class="inter1 inter"></div>
<div class="inter2 inter"></div>
<div>
We basically use the same value of top/left to have the following:
radial-gradient(circle at [left] [top],blue [radius],transparent [radius]);
I add 1px to transparent to avoid the jagged edge
If you feel comfortable with HTML <canvas> element it's probably your best friend for this type of task, I doubt there's a CSS way to achieve what you want.
(If there is a CSS way, it's probably going to be lot more complicated and have much slower perfomance than doing it with canvas anyway)
You can take a look at the code below to be inspired (source and live example)
<!DOCTYPE HTML>
<html>
<head>
<style>
body {
margin: 0px;
padding: 0px;
}
</style>
</head>
<body data-rsssl=1>
<canvas id="myCanvas" width="578" height="200"></canvas>
<script>
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
var x = canvas.width / 2;
var y = canvas.height / 2;
var radius = 75;
var offset = 50;
/*
* save() allows us to save the canvas context before
* defining the clipping region so that we can return
* to the default state later on
*/
context.save();
context.beginPath();
context.arc(x, y, radius, 0, 2 * Math.PI, false);
context.clip();
// draw blue circle inside clipping region
context.beginPath();
context.arc(x - offset, y - offset, radius, 0, 2 * Math.PI, false);
context.fillStyle = 'blue';
context.fill();
// draw yellow circle inside clipping region
context.beginPath();
context.arc(x + offset, y, radius, 0, 2 * Math.PI, false);
context.fillStyle = 'yellow';
context.fill();
// draw red circle inside clipping region
context.beginPath();
context.arc(x, y + offset, radius, 0, 2 * Math.PI, false);
context.fillStyle = 'red';
context.fill();
/*
* restore() restores the canvas context to its original state
* before we defined the clipping region
*/
context.restore();
context.beginPath();
context.arc(x, y, radius, 0, 2 * Math.PI, false);
context.lineWidth = 10;
context.strokeStyle = 'blue';
context.stroke();
</script>
</body>
</html>
What I mean is understood better in this photo
In the given photo, I used canvas for drawings; however, I would like to do it by an another way because I want to created rectangles be draggable and give ids to created rectangles. For example, If I used div instead of canvas, I could not manually draw the rectangles like in the photo. Maybe, there is a way but I don't know it. When I searched this subject, most of the people use paper.js, etc. but it is just useful in resize or drag&drop; therefore, I did not want to use these.
function lettersOnly(input) {
var regex = /[^a-z]/gi;
input.value = input.value.replace(regex, "");
}
jQuery(document).ready(function($) {
//Canvas
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
//Variables
var canvasOffset = $("#canvas").offset();
var canvasx = canvasOffset.left;
var canvasy = canvasOffset.top;
var last_mousex = 0;
var last_mousey = 0;
var mousex = 0;
var mousey = 0;
var mousedown = false;
var shapes = [];
var width;
var height;
// make var col a global variable
var col = "black";
var ad = "";
//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) {
const lastPos = {
lastMouseX: last_mousex,
lastMouseY: last_mousey,
rectWidth: width,
rectHeight: height,
// save the color of the rect
color: col,
name: ad
};
shapes.push(lastPos);
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);
width = mousex - last_mousex;
height = mousey - last_mousey;
col = $("#color").val();
ad = $("#name").val();
if (shapes.length > 0) {
for (var i in shapes) {
// for every shape in the shapes array beginPath
ctx.beginPath();
//set the color of the stroke
ctx.strokeStyle = shapes[i].color;
//draw the rect
ctx.rect(shapes[i].lastMouseX, shapes[i].lastMouseY, shapes[i].rectWidth, shapes[i].rectHeight);
ctx.fillText(shapes[i].name, shapes[i].rectWidth - shapes[i].lastMouseX, shapes[i].rectHeight - shapes[i].lastMouseY);
ctx.stroke();
}
}
//for the new rect beginPath
ctx.beginPath();
ctx.rect(last_mousex, last_mousey, width, height);
ctx.strokeStyle = col;
ctx.lineWidth = 3;
ctx.fillText(ad, 100, 100);
ctx.stroke();
}
$('#output').html('Current Coordinate: ' + mousex + ', ' + mousey + '<br/>Last Coordinate: ' + last_mousex + ', ' + last_mousey);
});
});
.topnav {
background-color: #333;
overflow: hidden;
}
/* Style the links inside the navigation bar */
.topnav a {
float: left;
color: #f2f2f2;
text-align: center;
padding: 14px 16px;
text-decoration: none;
font-size: 14px;
}
/* Change the color of links on hover */
.topnav a:hover {
background-color: #ddd;
color: black;
}
/* Add a color to the active/current link */
.topnav a.active {
background-color: #4CAF50;
color: white;
}
#color {
border: 1px solid black;
font-family: 'Times New Roman', Times, serif;
font-size: 14px;
margin: auto;
padding: 0;
position: absolute;
top: 0;
left: 45%;
right: 0;
text-align: center;
}
#name {
border: 1px solid black;
font-family: 'Times New Roman', Times, serif;
font-size: 14px;
margin: auto;
padding: 0;
position: absolute;
top: 0;
left: 45%;
right: 0;
text-align: center;
}
.submit {
border: 1px solid black;
margin: auto;
padding: 0;
width: 70px;
height: 30px;
position: absolute;
top: 0;
left: 0;
right: 0;
font-family: 'Times New Roman', Times, serif;
font-size: 14px;
text-align: center;
}
#canvas {
cursor: crosshair;
background-image: url("kroki2v3.png");
background-repeat: no-repeat;
background-size: contain;
padding: 0;
margin-left: 210;
margin-top: 160;
position: static;
display: block;
}
#output {
font-family: 'Times New Roman', Times, serif;
font-size: 14px;
top: 19%;
left: 46%;
position: absolute;
}
<html>
<head>
<meta charset="utf-8" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<div>
<table>
<tr>
<td><input type="text" id="color" style="margin-top: 70px" placeholder="Color" onkeyup="lettersOnly(this)" /></td>
<td><input type="text" id="name" style="margin-top: 100px;" placeholder="Department Name" onkeyup="lettersOnly(this)" /></td>
<td><input type="submit" class="submit" value="Submit" style="margin-top: 130px;" /></td>
</tr>
</table>
</div>
<div class="topnav">
<a class="active" href="">Project</a>
Contact
About
</div>
<div id="container" style="display: none;"><img src="kroki2v3.png" id="img01" alt="" style="display: none;"></div>
<canvas id="canvas" width="1200" height="520"></canvas>
<div id="output"></div>
</body>
</html>
Something like this? When you say "draw", this is what I imagined.
You need to find the mouse position in the mousedown function and in the mousemove function, then subtract the mousedown x and y position from the mousemove x and y position to set the width and height.
You also need to set a variable to tell whether or not the mouse is actually down while moving the mouse to ensure a div isn't "drawn" without knowledge.
Once you "mouseup" you can set your draggable / resizable functions to be used.
Here is a fiddle;
$(function() {
var widget;
var x;
var y;
var finX;
var finY;
var ismousedown = false;
$(document).on({
mousedown: function(event) {
if ($(event.target).attr('class') == 'wrapper') {
x = event.pageX;
y = event.pageY;
$('body').append('<div class="widget" style="top:' + y + 'px; left: ' + x + 'px;"></div>');
widget = $('.widget').last();
ismousedown = true;
}
},
mousemove: function(event) {
if (ismousedown == true) {
finX = event.pageX;
finY = event.pageY;
widget.width(finX - x);
widget.height(finY - y);
widget.css({
'width': (finX - x) + '!important',
'height': (finY - y) + '!important',
'display': 'block',
'border': '2px dashed #ccc'
});
}
},
mouseup: function(event) {
ismousedown = false;
widget.css({
'background': '#222',
'border': '0',
'cursor': 'move'
});
initDraggable();
}
});
// in case you need to reinitialize later.
function initDraggable() {
$('.widget').draggable({});
}
});
html,
body {
height: 100% !important;
position: relative;
}
.wrapper {
position: relative;
height: 100% !important;
width: 100% !important;
}
.widget {
display: block;
position: absolute;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<div class="wrapper">
</div>
I want to move div according to mouse position within the parent div after click on it.When we leave the mouse pointer then set the div position.
I have searched everywhere and it has led me to over-complicated ways of doing the same thing and involves the use of j-query. I need to strictly use javascript for what I am trying to do.
it's css code
body {
margin: 0px;
padding: 0px;
}
.crop-container{
width: 500px;
height: 500px;
border:5px solid black;
position: relative;
}
.crop-lense{
width: 100px;
height: 100px;
border: 5px dotted black;
position: relative;
z-index: 10;
resize: both;
background-color: transparent;
}
It's html code
<div class="crop-container" id="container" onmousemove="showCoords(event)">
<div class="crop-lense" id="lense">
</div>
</div>
It's javascript code
var lense = document.getElementById('lense');
var container = document.getElementById("container");
var lensemflag = false;
var x;
var y;
lense.addEventListener('mousedown',function(){
lensemflag = true;
console.log(lensemflag);
});
lense.addEventListener('mouseup',function(){
lensemflag = false;
console.log(lensemflag);
});
function showCoords(event) {
x = event.offsetX;
y = event.offsetY;
y = y - 50;
x = x - 50;
}
if(lensemflag==true){
setInterval(function() {
lense.style.top = y + 'px';
lense.style.left = x + 'px';
},
1);
}
Shortest answer:
var lense = document.getElementById("lense");
var container = document.getElementById("container");
var x;
var y;
lense.addEventListener("mousedown", function() {
lense.addEventListener("mousemove", showCoords)
});
lense.addEventListener("mouseup", removeListener);
lense.addEventListener("mouseout", removeListener);
function removeListener() {
lense.removeEventListener("mousemove", showCoords)
}
function showCoords(event) {
if(container.offsetWidth >= event.pageX + lense.offsetWidth / 2 + 10 &&
container.offsetHeight >= event.pageY + lense.offsetHeight / 2 + 10 &&
event.pageX - lense.offsetWidth / 2 > 0 &&
event.pageY - lense.offsetHeight / 2 > 0){
x = event.pageX - lense.offsetWidth / 2;
y = event.pageY - lense.offsetHeight / 2;
lense.style.top = y + "px";
lense.style.left = x + "px";
}
}
body {
margin: 0px;
padding: 0px;
}
.crop-container{
width: 500px;
height: 500px;
border:5px solid black;
position: relative;
}
.crop-lense{
width: 100px;
height: 100px;
border: 5px dotted black;
position: relative;
z-index: 10;
resize: both;
background-color: transparent;
t
}
<div class="crop-container" id="container">
<div class="crop-lense" id="lense">
</div>
</div>
I am 3th year at college and for web design class we are manually drawing canvas elements. Which is very boring for me so I tried to make some 2D paint where I can do it by mouse where on the other end it writes code by itself.
I managed to do this much even tho is not "much" but now I am wondering is there a way to undo some script to remove it from the code? One way would be to append new canvas and do moves by one less but is there something to delete existing ones but not to recreate new ones over and over again?
In this example down below (try by full screen), when I add new lines I add new moves to the array and when I finish at the starting point I can draw new element. But every time I add new line I re create or draw lines over existing ones and new lines so it shows as one element where I could fill style and so on.
By doing that you will see that the adding lines over existing ones create a little darker bolder line, and because of that I would like to know if there is some way to delete or undo those lines and add whole new ones without puting em over existing ones.
$(document).ready(function(){
var mainCanvas = $('#mainCanvas')[0].getContext('2d');
var coordsCanvas = $('#coordsCanvas')[0].getContext('2d');
var moves = [];
$('#newCoords').click(function(){
var mainCanvasWidth = $('#mainCanvas').width();
$(this).parent().prepend('<input class="input-class" id="x-n0" placeholder="X number of blocks"><input class="input-class" id="y-n0" placeholder="Y number of blocks"> <span class="notes">Note: canvas full width is: '+Math.floor(mainCanvasWidth)+'px. </span><button id="saveCoords">Save</button>')
$(this).remove();
});
$(document).on('click','#saveCoords',function(){
var x = $(this).siblings('input#x-n0').val(),
y = $(this).siblings('input#y-n0').val(),
mainCanvasWidth = $('#mainCanvas').width(),
mainCanvasHeight = $('#mainCanvas').height(),
xWidthPx = Math.floor(mainCanvasWidth/x),
yHeightPx = Math.floor(mainCanvasHeight/y);
$('#coordsCanvas, #mainCanvas').attr('width', Math.floor(xWidthPx*x));
$('#coordsCanvas, #mainCanvas').attr('height', Math.floor(yHeightPx*y));
var marginLeftRight = 'calc(50% - '+Math.floor(xWidthPx*x)/2+'px)';
$('#coordsCanvas, #mainCanvas').css({'width':Math.floor(xWidthPx*x)+'px','height':Math.floor(yHeightPx*y)+'px','left': marginLeftRight, 'top':'10vh'});
for(var i=0; i<x-1; i++){
coordsCanvas.beginPath();
coordsCanvas.moveTo(Math.floor(xWidthPx+(xWidthPx*i)), 0);
coordsCanvas.lineTo(Math.floor(xWidthPx+(xWidthPx*i)), Math.floor(yHeightPx*y));
coordsCanvas.stroke();
coordsCanvas.closePath();
}
for(var i=0; i<y-1; i++){
coordsCanvas.beginPath();
coordsCanvas.moveTo(0 ,Math.floor(yHeightPx+(yHeightPx*i))+1);
coordsCanvas.lineTo(Math.floor(xWidthPx*x), Math.floor(yHeightPx+(yHeightPx*i))+1);
coordsCanvas.stroke();
coordsCanvas.closePath();
}
$(this).parent().html('<label for="#mouse-position"><input type="checkbox" id="mouse-position">Show mouse position</label><span class="notes">X = '+Math.floor(xWidthPx)+'px; Y = '+Math.floor(yHeightPx)+'px;</span><div class="tools"><button id="line">Lines</button></div>');
});
$(document).on( "change", "#mouse-position", function() {
if($('input[id="mouse-position"]:checked').length === 1){
$('#mouse-coords').css('display','block');
}else{
$('#mouse-coords').css('display','none');
}
});
$(document).on( "click", "#line", function() {
$(this).css('background','silver');
$('#mainCanvas').css({'cursor':'url(./pen.png) 0 24, auto'});
});
$(document).on( "click", "#mainCanvas", function(e) {
var cursor = $('#mainCanvas').css('cursor');
var strokeStyle = $('#strokestyle').val();
if(~cursor.indexOf('pen.png')){
var posX = $(this).position().left,
posY = $(this).position().top;
if(moves[0]==='beginPath'){
if(Object.keys(moves[1])[0]==='moveTo'){
var len = moves.length-1,
nowpos = Math.floor((e.pageX - posX)) + ',' + Math.floor((e.pageY - posY)),
renderDrawing = [];
renderDrawing.push({'func': 'beginPath', init: function(){ mainCanvas.beginPath(); }});
if(moves[len]!=="stroke" || moves[len]!=="closePath"){
for(var ee=1; ee<moves.length; ee++){
if(Object.keys(moves[ee])[0]==="moveTo"){
var mtp = moves[ee]['moveTo'],
pos = mtp.split(',');
renderDrawing.push({func: 'moveTo', val: pos, init: function(){
mainCanvas.moveTo(this.val[0], this.val[1]);
}});
}else if(Object.keys(moves[ee])[0]==="lineTo"){
var mtp = moves[ee]['lineTo'],
pos = mtp.split(',');
renderDrawing.push({func: 'lineTo', val: pos, init: function(){
mainCanvas.lineTo(this.val[0], this.val[1]);
}});
}
}
var nowX = Math.floor((e.pageX - posX));
var nowY = Math.floor((e.pageY - posY));
var nowXY = nowX + ',' + nowY;
moves.push({'lineTo':nowXY});
renderDrawing.push(
{func: 'lineTo', val: nowXY, init: function(){
mainCanvas.lineTo(this.val.split(',')[0], this.val.split(',')[1]);
}},
{func: 'stroke', init: function(){ mainCanvas.stroke(); }},
{func: 'closePath', init: function(){ mainCanvas.closePath(); }});
for(var q=0; q<renderDrawing.length; q++){
if(renderDrawing[q]['func']!=="beginPath" && renderDrawing[q]['func']!=="closePath" && renderDrawing[q]['func']!=="stroke"){
renderDrawing[q].init();
}else renderDrawing[q].init();
}
console.log(moves);
if(Object.keys(moves[len])[0]==="lineTo" && nowpos===moves[1]['moveTo']){
moves = [];
}
}
}
}else{
mainCanvas.beginPath();
mainCanvas.moveTo(Math.floor(e.pageX - posX) , Math.floor(e.pageY - posY));
moves.push('beginPath',{'moveTo':Math.floor((e.pageX - posX)) + ',' + Math.floor((e.pageY - posY))});
console.log(moves);
}
}
});
$(document).on('mousemove', "#mainCanvas", function(e){
var parentOffset = $('#mainCanvas').offset();
var relX = e.pageX - parentOffset.left;
var relY = e.pageY - parentOffset.top;
$('#mouse-coords').css({
left: e.pageX + 20,
top: e.pageY
}).text( "X: " + Math.floor(relX) + ", Y: " + Math.floor(relY) );
});
});
* {
margin: 0;
padding: 0;
list-style: none;
text-decoration: none;
box-sizing: border-box;
}
body {
overflow: hidden;
font-size: 100%;
}
.container {
width: 100vw;
height: 100vh;
padding-right: 5vw;
padding-left: 5vw;
padding-top: 10vh;
padding-bottom: 5vh;
overflow: hidden;
position: relative;
}
canvas {
width: 90vw;
height: 85vh;
border: 1px solid #000;
float: left;
}
.toolsBar {
width: calc(100% - 10vw);
position: absolute;
top: 5px;
left: 5vw;
border: 1px solid #000;
height: calc(10vh - 10px);
overflow: hidden;
overflow-y: auto;
}
button {
color: #fff;
background: skyblue;
border: 0;
border-radius: 5px;
margin: 5px;
padding: 15px;
cursor: pointer;
float: left;
}
.input-class {
border-radius: 5px;
margin: 5px;
padding: 15px;
float: left;
border: 1px solid #e0e0e0;
outline: none;
}
.notes {
display: inline-block;
height: 60px;
text-align: center;
float: left;
color: red;
line-height: 60px;
}
#mouse-coords {
position: absolute;
display: none;
background: #000;
padding: 2px;
color: #fff;
}
label[for="#mouse-position"] {
display: inline-block;
height: 60px;
text-align: center;
line-height: 60px;
font-size: 1.2rem;
float: left;
padding: 5px;
}
label>input {
height: 1.2rem;
width: 1.2rem;
}
.coordsCanvas {
position: absolute;
z-index: 100;
}
#mainCanvas {
background: rgba(255,255,255,.5);
position: absolute;
z-index: 200;
}
.tools {
width: auto;
overflow: hidden;
overflow-y: auto;
height: 100%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<div class="toolsBar">
<button id="newCoords">X & Y</button>
</div>
<div id="mouse-coords"></div>
<canvas class="coordsCanvas" id="coordsCanvas"></canvas>
<canvas id="mainCanvas"></canvas>
</div>
I want to save and restore data from div - that is container of other divs,
In order to make it I use local storage and JSON like this:
window.onload = restoreJason;
function makeJson(){
var canvas = document.getElementById("canvas");
var shapes = canvas.querySelectorAll("div[class='drag']");
var divs = new Object();
for(var i=0; i<shapes.length; ++i){
divs[shapes[i].getAttribute('innerHTML')] = shapes[i].innerHTML;
}
localStorage.setItem("divs", JSON.stringify(divs));
}
function restoreJason(){
var divs = JSON.parse(localStorage.getItem("divs"));
var canvas = document.getElementById("canvas");
var shapes = canvas.querySelectorAll("div[class='drag']");
for(var i = 0; i<shapes.length; i++){
shapes[i].value = divs[shapes[i].getAttribute("innerHTML")];
}
console.log(divs);
}
However, I don't know how to access the innerHTML of the elements and save it or restore it.
What do you think I shall do?
(To be more detailed - I need to save the content of the div when user click on "save", and load it when the user click "load". This is a snippest of it...)
NOTICE: the "canvas" is just the id of the main div, and not a real "canvas".
function randomizeColor() {
var letters = '0123456789ABCDEF';
var color = '#';
for (var i = 0; i < 6; i++) {
color += letters[Math.floor(Math.random() * letters.length)];
}
return color;
}
function randomizeRectangle() {
var width = Math.random() * 700 + 50;
var height = Math.random() * 250 + 50;
if (height <= 20) {
height = 20;
}
var posX = Math.round(Math.random() * window.innerWidth);
var posY = Math.round(Math.random() * window.innerHeight);
var randomRecObj = {
"width": width + "px",
"height": height + "px",
"posX": posX,
"posY": posY
};
return randomRecObj;
}
function makeShape() {
var rect = randomizeRectangle();
var rectDOM = document.createElement("div");
rectDOM.className = "rectangle";
rectDOM.style.border = "1px solid black";
rectDOM.style.width = rect.width;
rectDOM.style.height = rect.height;
rectDOM.style.background = randomizeColor();
rectDOM.style.top = rect.posY + "px";
rectDOM.style.left = rect.posX + "px";
//rectDOM.addEventListener("click", selectShape);
// rectDOM.style.transform =rect.rotation;
return rectDOM;
}
function randRect() {
var rectDOM = makeShape();
var canvas = document.getElementById("canvas");
canvas.appendChild(rectDOM);
}
function randOval() {
var ovalDOM = makeShape();
ovalDOM.style.borderRadius = "50%";
var canvas = document.getElementById("canvas");
canvas.appendChild(ovalDOM);
}
function changeColor(){
}
function cancelSelection() {
var selected = document.getElementsByClassName("selected");
while (selected) {
selected[0].classList.remove(selected[0]);
}
}
function removeShape(event) {
var selectedShapes = document.getElementsByClassName("selected");
var len = selectedShapes.length;
while (len > 0) {
selectedShapes[0].parentNode.removeChild(selectedShapes[0]);
--len;
}
}
function removeCorners(rectDom) {
var corners = document.getElementsByClassName("corners");
var len = corners.length;
while (len > 0) {
corners[0].classList.remove("corners");
--len;
}
}
.header{
background: #4ABDAC;
color: #fff;
margin: 1px;
}
hr{
border-top: 3px double #2a3132;
}
ul{
list-style: none;
margin: 0;
padding: 0;
overflow: hidden;
background-color: #90afc5;
}
li{
float: left;
border: 2px solid #336b87;
padding: 3px;
margin: 3px;
}
li>a{
display: block;
color: #2a3132;
text-decoration: none;
padding: 10px 14px;
}
#color{
margin-left: 150px;
}
#rect{
margin-left: 100px;
}
li>a:hover{
color: #763626;
cursor: pointer;
}
#canvas{
background: #66a5ad;
position: relative;
height: 1200px;
width: 100%;
}
.corners{
position: absolute;
height: 10px;
width: 10px;
background:#fff;
border: 1px solid black;
display: none;
}
.selected .corners{
display: inline-block;
}
.cornerUpLeft{
top: -5px;
left: -5px;
}
.cornerUpRight{
top: -5px;
right: -5px;
}
.cornerBtmLeft{
bottom: -5px;
left: -5px;
}
.cornerBtmRight{
bottom: -5px;
right: -5px;
}
.rectangle{
position: absolute;
}
.colorBox{
border: 1px solid black;
height: 20px;
width: 20px;
list-style: none;
}
<!DOCTYPE html>
<html lang="en">
<head>
<title>Sketch Board - Eyal Segal Project</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="css/style.css" rel="stylesheet">
<script src="js/sketch.js"></script>
</head>
<body>
<h1 class="header">Sketch Board</h1>
<div>
<ul class="toolbar">
<li><a>Load</a></li>
<li id="Save"><a>Save</a></li>
<li id="rect"><a onclick="randRect()">Rectangle</a></li>
<li><a onclick="randOval()">Oval</a></li>
</ul>
<hr>
</div>
<div class="canvas" id="canvas">
</div>
</body>
</html>
All you need to do is set the .innerHTML of the div id="canvas" into localStorage. There's no need for JSON or loops at all.
Also, don't use inline HTML event attributes (onclick). Instead, do all your JavaScript separately using modern, standards based event handling.
Lastly, there is no need for <a> elements to be able to respond to a click event. Actually, your a elements are invalid as they don't have a name or href attribute anyway. The li elements can simply be set up for click events.
This is the code to do it but it won't execute here in the Stack Overflow snippet environment, but you can see it working here.
// Get reference to the "canvas"
var can = document.getElementById("canvas");
// Save the content of the canvas to localStorage
function saveData(){
localStorage.setItem("canvas", can.innerHTML);
}
// Get localStorage data
function restoreData(){
can.innerHTML = localStorage.getItem("canvas");
}
// get load and save references
var load = document.getElementById("load");
var save = document.getElementById("save");
// Set up event handlers
load.addEventListener("click", restoreData);
save.addEventListener("click", saveData);
// Get references to the rect and oval "buttons" and set their event handlers
var rect = document.getElementById("rect");
rect.addEventListener("click", randRect);
var oval = document.getElementById("oval");
oval.addEventListener("click", randOval);
function randomizeColor() {
var letters = '0123456789ABCDEF';
var color = '#';
for (var i = 0; i < 6; i++) {
color += letters[Math.floor(Math.random() * letters.length)];
}
return color;
}
function randomizeRectangle() {
var width = Math.random() * 700 + 50;
var height = Math.random() * 250 + 50;
if (height <= 20) {
height = 20;
}
var posX = Math.round(Math.random() * window.innerWidth);
var posY = Math.round(Math.random() * window.innerHeight);
var randomRecObj = {
"width": width + "px",
"height": height + "px",
"posX": posX,
"posY": posY
};
return randomRecObj;
}
function makeShape() {
var rect = randomizeRectangle();
var rectDOM = document.createElement("div");
rectDOM.className = "rectangle";
rectDOM.style.border = "1px solid black";
rectDOM.style.width = rect.width;
rectDOM.style.height = rect.height;
rectDOM.style.background = randomizeColor();
rectDOM.style.top = rect.posY + "px";
rectDOM.style.left = rect.posX + "px";
//rectDOM.addEventListener("click", selectShape);
// rectDOM.style.transform =rect.rotation;
return rectDOM;
}
function randRect() {
var rectDOM = makeShape();
var canvas = document.getElementById("canvas");
canvas.appendChild(rectDOM);
}
function randOval() {
var ovalDOM = makeShape();
ovalDOM.style.borderRadius = "50%";
var canvas = document.getElementById("canvas");
canvas.appendChild(ovalDOM);
}
function changeColor(){
}
function cancelSelection() {
var selected = document.getElementsByClassName("selected");
while (selected) {
selected[0].classList.remove(selected[0]);
}
}
function removeShape(event) {
var selectedShapes = document.getElementsByClassName("selected");
var len = selectedShapes.length;
while (len > 0) {
selectedShapes[0].parentNode.removeChild(selectedShapes[0]);
--len;
}
}
function removeCorners(rectDom) {
var corners = document.getElementsByClassName("corners");
var len = corners.length;
while (len > 0) {
corners[0].classList.remove("corners");
--len;
}
}
.header{
background: #4ABDAC;
color: #fff;
margin: 1px;
}
hr{
border-top: 3px double #2a3132;
}
ul{
list-style: none;
margin: 0;
padding: 0;
overflow: hidden;
background-color: #90afc5;
}
li{
float: left;
border: 2px solid #336b87;
padding: 3px;
margin: 3px;
}
li>a{
display: block;
color: #2a3132;
text-decoration: none;
padding: 10px 14px;
}
#color{
margin-left: 150px;
}
#rect{
margin-left: 100px;
}
li>a:hover{
color: #763626;
cursor: pointer;
}
#canvas{
background: #66a5ad;
position: relative;
height: 1200px;
width: 100%;
}
.corners{
position: absolute;
height: 10px;
width: 10px;
background:#fff;
border: 1px solid black;
display: none;
}
.selected .corners{
display: inline-block;
}
.cornerUpLeft{
top: -5px;
left: -5px;
}
.cornerUpRight{
top: -5px;
right: -5px;
}
.cornerBtmLeft{
bottom: -5px;
left: -5px;
}
.cornerBtmRight{
bottom: -5px;
right: -5px;
}
.rectangle{
position: absolute;
}
.colorBox{
border: 1px solid black;
height: 20px;
width: 20px;
list-style: none;
}
<h1 class="header">Sketch Board</h1>
<div>
<ul class="toolbar">
<li id="load">Load</li>
<li id="save">Save</li>
<li id="rect">Rectangle</li>
<li id="oval">Oval</li>
</ul>
<hr>
</div>
<div class="canvas" id="canvas">
</div>