How to draw a rectangle manually in html without canvas? - javascript

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>

Related

How do I move the position of canvas using either css or javascript?

this is my first question here. I am fairly new to html, css, and javascript.
What I wanted to achieve was similar to this mockup i've created:
my website mockup
I've tried to replace the rectangle on the left side with javascript code to achieve a similar effect. The javascript code was taken from this codepen:
https://codepen.io/vaaghu/pen/abmYGYz
I've nudged the canvas a bit to the right, but if i extend the canvas width and height, the canvas does extend, but the circle animations don't. How do I extend this animation?
var canvas = document.querySelector("canvas")
canvas.width = 800;
canvas.height = 1600;
var c = canvas.getContext("2d");
var mouse = {x:innerWidth/2,y:innerHeight/2}
window.addEventListener("mousemove",(event)=>{
mouse.x = event.x;
mouse.y = event.y;
})
window.addEventListener("resize",()=>{
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
int();
})
function Circle(x, y,dx,dy,radius,color) {
this.x = x;
this.y = y;
this.dx = dx;
this.dy = dy;
this.radius = radius;
this.color = color
var maxRadius = 30;
this.draw = function() {
c.beginPath();
c.arc(this.x,this.y,this.radius,0,Math.PI * 2,false);
c.fillStyle = color
c.fill();
}
this.update = function(){
if(this.x+this.radius > innerWidth || this.x-this.radius < 0) {
this.dx = -this.dx;
}
if(this.y+this.radius > innerHeight || this.y -this.radius < 0 ) {
this.dy = -this.dy;
}
if( mouse.x - this.x > -50 && mouse.x - this.x < 50 && mouse.y - this.y >-50 && mouse.y - this.y < 50) {
if (this.radius < maxRadius) {
this.radius += 1
}
} else {
if (this.radius > radius) {
this.radius -= 1
}
}
this.x += this.dx;
this.y += this.dy;
this.draw();
}
}
var colorArray = ["#F5871A","#81968F","#DFAA2F","#D76034","#F5411D"];
var circleArray = []
function int() {
circleArray = []
for (let i = 0; i < 700; i++) {
var x = Math.random() * window.innerWidth;
var y = Math.random() * (window.innerHeight ) ;
var radius = Math.random() * 5 + 2;
var dx = Math.random() - 0.5;
var dy = Math.random() - 0.5;
var color = colorArray[Math.floor(Math.random()*4)]
circleArray.push(new Circle(x,y,dx,dy,radius,color))
}
}
int()
function animate() {
requestAnimationFrame(animate);
c.clearRect(0,0,innerWidth,innerHeight)
for (let i = 0; i < circleArray.length; i++) {
circleArray[i].update()
}
}
animate();
.mediaViewInfo {
--web-view-name: Homepage;
--web-view-id: Homepage;
--web-scale-on-resize: true;
--web-show-navigation-controls: true;
--web-enable-deep-linking: true;
--web-page-font: arial, Manrope;
}
:root {
--web-view-ids: Homepage;
}
* {
margin: 0;
padding: 0;
box-sizing: border-box;
border: none;
}
#Homepage {
position: absolute;
width: 100%;
height:450%;
font-family: arial, Manrope;
background-color: rgba(255,255,255,1);
overflow: hidden;
--web-view-name: Homepage;
--web-view-id: Homepage;
--web-scale-on-resize: true;
--web-show-navigation-controls: true;
--web-enable-deep-linking: true;
--web-page-font: arial;
}
canvas {
background: #FFFF05;
background-image: linear-gradient(to bottom, #81968F99, #FFE636CC, #FF000066);
margin: 50% 0% 0% 8%;
padding: 0vh 0vh 0vh 0vh;
z-index:-1;
width:auto;
}
#Wave_Vid {
position: absolute;
left: -19px;
top: -1920px;
width: 100vh;
height: 100vh;
overflow: hidden;
}
.Wave_container {
overflow: visible;
}
#MIDDLEcontainer {
position:absolute;
top: 24%;
left:59%;
}
#MIDDLE {
overflow: visible;
}
#Good_ideas_can_take_time {
line-height: 0.8;
width: 100%;
text-align: left;
padding-right: 10%;
font-family: Manrope, arial;
font-style: normal;
font-weight: bold;
font-size: 15vh;
color: rgba(129,150,143,1);
margin-bottom: 30px;
}
#And_execution_takes_even_more {
width: 100%;
line-height: 1em;
text-align: left;
padding-right: 30vh;
font-family: Manrope, arial;
font-style: normal;
font-weight: normal;
font-size: 5vh;
color: rgba(129,150,143,1);
margin-bottom: 20px;
}
#Line_ {
fill: transparent;
stroke: rgba(129,150,143,1);
stroke-width: 4px;
stroke-linejoin: miter;
stroke-linecap: butt;
stroke-miterlimit: 4;
shape-rendering: auto;
}
.Line_ {
width: 509px;
height: 10px;
transform: matrix(1,0,0,1,0,0);
margin-bottom: 40px;
}
#Midcontainer {
position:absolute;
}
#Mid {
float:bottom;
position:absolute;
}
.MySkills {
position: relative;
overflow:visible;
height: 1em;
text-align: left;
font-family: Manrope, arial;
font-style: normal;
font-weight: lighter;
font-size: 12vh;
color: rgba(129,150,143,1);
letter-spacing: -0.85px;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>wbdg portfolio</title>
<link rel="stylesheet" type="text/css" id="applicationStylesheet" href="../faux styles.css"/>
</head>
<body>
<div>
<canvas></canvas>
<script id="jssomething" type="text/javascript" src="../faux scripts.js"></script>
<script src="https://kit.fontawesome.com/4f3ce16e3e.js" crossorigin="anonymous"></script>
<div id="MIDDLEcontainer">
<div id="MIDDLE">
<div id="Good_ideas_can_take_time">
<p>Good ideas can take time.</p>
</div>
<div id="And_execution_takes_even_more">
<span>And execution takes even more.</span>
</div>
<svg class="Line_" viewBox="0 0 674 4">
<path id="Line_" d="M 0 0 L 674 0">
</path>
</svg>
<div id="Midcontainer">
<div id="Mid">
<div class="MySkills"> Photos </div>
<div class="MySkills"> Illustrations </div>
<div class="MySkills"> Videos </div>
<div class="MySkills"> Animations </div>
<div class="MySkills"> Branding </div>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
If I understand correctly, change these lines in int() function:
var x = Math.random() * window.innerWidth;
var y = Math.random() * (window.innerHeight ) ;
to this:
var x = Math.random() * canvas.width;
var y = Math.random() * canvas.height;

Javascript div box that follow cursor position

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>

Can I undo or delete some javascript code after running it

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>

How to save innerHTML of div in a local storage?

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>

My color selector isnt working with my canvas

I have tried to add in a color selector for my drawing app, The color selector works fin but when i draw it just appears in black. Here is my JSFIDDLE
You can see if you click on the right hand side of my toolbar is the color picker and you will see that the color picker works perfectly but when you select a color it will not draw as the color, If you find a solution please update the JSFiddle and link it so a can go through it and analyse.
my html:
<!doctype html>
<html>
<head>
<link rel="shortcut icon" type="image/x-icon" href="SiteIcon.ico">
<title>Canvas</title>
<link rel="stylesheet" href="master.css">
<script type="text/javascript">
function processData(c1, c2) {
var cv1 = document.getElementById(c1).value;
var cv2 = document.getElementById(c2).value;
alert(cv1 + "\n" + cv2);
}
</script>
</head>
<span style="cursor:crosshair">
<body style='margin: 0'>
<div id="toolbar">
<div id="rad">
Radius <span id="radval">10</span>
<div id="decrad" class="radcontrol">-</div>
<div id="incrad" class="radcontrol">+</div> <font color="white">BACK</font>
<font color="white">CLEAR</font>
</div>
<div id="colors">
Colour:
<input type="color" name="color1" id="color1" />
<br />
<br />
</div>
<canvas id="canvas" style="display: block;">sorry, your browser does not support our canvas tag.</canvas>
<script src="main.js"></script>
<script src="toolbar.js"></script>
<script src="pallet.js"></script>
</span>
<br>
</body>
</html>
my css:
* {
box-sizing: border-box;
-moz-box-sizing: border-box;
font-family: sans-serif;
user-select: none;
-webkit-user-select:none;
-moz-user-select:none;
-ms-user-select:none;
}
#toolbar {
width: 100%;
height: 50px;
padding: 10px;
position: fixed;
top: 0;
background-color: #2f2f2f;
color: white;
}
.radcontrol {
width: 30px;
height: 30px;
background-color: #4f4f4f;
display: inline-block;
text-align: center;
padding: 5px;
}
#rad {
float: left;
}
#colors {
float: right;
}
.swatch {
width: 30px;
height: 30px;
border-radius: 15px;
box-shadow: inset 0px 1px 0px rgba(255, 255, 255, 0.5), 0px 2px 2px rgba(0, 0, 0, 0.5);
display: inline-block;
margin-left: 10px;
}
.swatch.active {
border: 2px solid white;
box-shadow: inset 0px 1px 2px rgba(0, 0, 0, 0.5);
}
#back {
width: 60px;
height: 5px;
padding: 5%;
background-color: white;
}
my javascript:
var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');
var radius = 10;
var dragging = false;
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
context.lineWidth = radius * 2;
var putPoint = function (e) {
if (dragging) {
var bounds = canvas.getBoundingClientRect();
var mouseX = e.clientX + bounds.left;
var mouseY = e.clientY - bounds.top;
var mouseX = e.clientX + bounds.left - 20;
context.lineTo(mouseX, mouseY)
context.stroke();
context.beginPath();
context.arc(mouseX, mouseY, radius, 0, Math.PI * 2);
context.fill();
context.beginPath();
context.moveTo(mouseX, mouseY);
}
}
var engage = function (e) {
dragging = true;
putPoint(e);
}
var disengage = function () {
dragging = false;
context.beginPath();
}
canvas.addEventListener('mousedown', engage);
canvas.addEventListener('mousemove', putPoint);
canvas.addEventListener('mouseup', disengage);
var setRadius = function (newRadius) {
if (newRadius < minRad) newRadius = minRad;
else if (newRadius > maxRad) newRadius = maxRad;
radius = newRadius;
context.lineWidth = radius * 2;
radSpan.innerHTML = radius;
}
var minRad = 1,
maxRad = 100,
defaultRad = 20,
interval = 5,
radSpan = document.getElementById('radval'),
decRad = document.getElementById('decrad'),
incRad = document.getElementById('incrad');
decRad.addEventListener('click', function () {
setRadius(radius - interval);
});
incRad.addEventListener('click', function () {
setRadius(radius + interval);
});
setRadius(defaultRad);
Solution Fiddle:
http://jsfiddle.net/CJ_/egpr99k9/22/
You need to define a strokeStyle and fillStyle in order to change the colour drawn to canvas (see below). The colour input dom element won't automatically change the colour for you, you need to fetch it through document.getElementById('color1').value.
var putPoint = function (e) {
if (dragging) {
var bounds = canvas.getBoundingClientRect();
var mouseX = e.clientX + bounds.left;
var mouseY = e.clientY - bounds.top;
var mouseX = e.clientX + bounds.left - 20;
context.lineTo(mouseX, mouseY)
context.strokeStyle = document.getElementById('color1').value;
context.stroke();
context.beginPath();
context.arc(mouseX, mouseY, radius, 0, Math.PI * 2);
context.fillStyle = document.getElementById('color1').value;
context.fill();
context.beginPath();
context.moveTo(mouseX, mouseY);
}
}

Categories

Resources