HTML javascript, dragging method in canvas - javascript

I made a square grid using HTML canvas and I am implementing a drag mechanism, such that the user can draw only rectangles by dragging over the grid.
In the below solution, the user can draw non-rectangle shapes, depending on how the user drags.
An additional question : The grid can be of any size and the drag operation is laggy for large rectangles. Any performance improvement suggestions for that ?
Here are my code of html and javascript
function getSquare(canvas, evt) {
var rect = canvas.getBoundingClientRect();
return {
x: 1 + (evt.clientX - rect.left) - (evt.clientX - rect.left)%10,
y: 1 + (evt.clientY - rect.top) - (evt.clientY - rect.top)%10
};
}
function emptySquare(context) {
context.rect(0, 0, canvas.width, canvas.height);
context.fillStyle = "#ffffff"
context.fill();
context.strokeStyle = "#ddd";
context.stroke();
}
function range(start, end) {
var ans = [];
if (end > start) {
for (let i = start; i <= end; i += 10) {
ans.push(i);
}
} else {
emptySquare(context);
for (let i = start; i >= end; i -= 10) {
ans.push(i);
}}
return ans;
}
function drawBoard(context) {
for (var x = 0.5; x < 20001; x += 10) {
context.moveTo(x, 0);
context.lineTo(x,20000);
}
for (var y = 0.5; y < 20001; y += 10) {
context.moveTo(0, y);
context.lineTo(20000, y);
}
context.strokeStyle = "#ddd";
context.stroke();
}
function fillSquare(context, x, y){
context.fillStyle = "#70B7B5";
context.fillRect(x,y,9,9);
}
var canvas = document.getElementById('myBoard');
var context = canvas.getContext('2d');
var A;
drawBoard(context);
var isDrag= false;
// drawBoard(context);
canvas.addEventListener('mousedown', function(evt) {
var mousePos = getSquare(canvas, evt);
isDrag=true;
fillSquare(context, mousePos.x, mousePos.y);
previousPos = mousePos;
}, false);
canvas.addEventListener('mousemove', function(evt) {
if (isDrag) {
var mousePos = getSquare(canvas, evt);
var x_dist = range(previousPos.x, mousePos.x);
var y_dist = range(previousPos.y, mousePos.y);
for (x in x_dist) {
for (y in y_dist) {
fillSquare(context, x_dist[x], y_dist[y]);
}
}
}
}, false);
canvas.addEventListener('mouseup', function(evt) {
if (isDrag){
isDrag = false;
}
}, false);
var canvas = document.getElementById('myBoard');
var context = canvas.getContext('2d');
// drawBoard(context);
var isDrag=false;
canvas.addEventListener('mousedown', function(evt) {
var mousePos = getSquare(canvas, evt);
isDrag=true;
fillSquare(context, mousePos.x, mousePos.y);
previousPos = mousePos;
}, false);
canvas.addEventListener('mousemove', function(evt) {
if (isDrag) {
var mousePos = getSquare(canvas, evt);
var x_dist = range(previousPos.x, mousePos.x);
var y_dist = range(previousPos.y, mousePos.y);
for (x in x_dist) {
for (y in y_dist) {
fillSquare(context, x_dist[x], y_dist[y]);
}
}
}
}, false);
canvas.addEventListener('mouseup', function(evt) {
if (isDrag){
isDrag = false;
}
}, false);
<head>
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
<link rel="stylesheet" href="./assets/css/style.css">
<meta charset="utf-8">
</head>
<body>
<nav class="navbar navbar-expand-lg navbar-dark bg-dark">
<div class="container-fluid">
<a class="navbar-brand" href="index.html">t</a>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNavAltMarkup" aria-controls="navbarNavAltMarkup" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarNavAltMarkup">
<div class="navbar-nav">
<a class="nav-link" aria-current="page" href="index.html">Home</a>
<a class="nav-link" href="#">About Us</a>
<a class="nav-link" href="Myblock.html">Mk</a>
</div>
<div class="navbar-nav ms-auto mb-2 mb-lg-0">
<a class="nav-link" href="login.html">Login</a>
</div>
</div>
</div>
</nav>
<div>
<div class="modal fade bd-example-modal-lg" id="exampleModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">간판 구입</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<form action="" method="POST" enctype="multipart/form-data">
<div class="container">
<div class="row">
<div class="col-md-12">
<div class="form-group">
<div class="preview-zone hidden">
<div class="box box-solid">
<div class="box-header with-border">
<div><b>미리보기</b></div>
<!-- <div class="box-tools pull-right">
<button type="button" class="btn btn-danger btn-xs remove-preview">
<i class="fa fa-times"></i> 초기화
</button>
</div> -->
</div>
<div class="box-body"></div>
</div>
</div>
<div class="dropzone-wrapper">
<div class="dropzone-desc">
<i class="glyphicon glyphicon-download-alt"></i>
<p>광고 이미지 선택 or 드래그해 옮겨 오세요.</p>
</div>
<input type="file" name="img_logo" class="dropzone">
</div>
</div>
</div>
</div>
</div>
<div class="form-group">
<label for="exampleInputEmail1">닉네임/이름</label>
<input type="email" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" placeholder="닉네임/이름">
<label for="exampleInputEmail1">연락처</label>
<input type="email" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" placeholder="핸드폰 번호">
<label for="exampleInputEmail1">구매희망 면적</label>
<input type="email" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" placeholder="ex) 10 x 10 OR 100x100 ">
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">닫기</button>
<button type="submit" class="btn btn-dark">적용하기</button>
</div>
</div>
</div>
</div>
<div>
<canvas id="myBoard" width="1440" height="1200"></canvas>
</div>
</hr>
<footer>
<p>© 2021 Nune Project</p>
</footer>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.1.3/dist/js/bootstrap.bundle.min.js"></script>
<script type="text/javascript" src="./assets/js/mainBoard.js"></script>
<script type="text/javascript" src="./assets/js/drag_field.js"></script>
</body>

The issue is being seen because range function is not clearing the squares when end > start. Clearing the squares in both the cases resolves the issue.
Here's the snippet that fixes the issue.
function range(start, end) {
var ans = [];
emptySquare(context);
if (end > start) {
for (let i = start; i <= end; i += 10) {
ans.push(i);
}
} else {
for (let i = start; i >= end; i -= 10) {
ans.push(i);
}
}
return ans;
}
The Lag Issue
The callback function attached to mousemove clears and draws squares on every invocation - a time consuming operation. Given that JavaScript is single threaded and this function is called at a very high rate, it might be the cause of the lag.
Debouncing the mousemove callback can help reducing the lag.

Another approach to solve the lag issue is to make two canvases: one for the background grid lines and the other one for drawing the green rectangles.
<div>
<canvas id="bg" width="1440" height="1200"></canvas>
<canvas id="myBoard" width="1440" height="1200"></canvas>
</div>
Set the #bg canvas so that #myBoard is in front of it:
#bg {
position: absolute;
z-index: -1;
}
Then draw the grid lines on the #bg canvas:
const bg = document.getElementById('bg')
const bgContext = bg.getContext('2d')
drawBoard(bgContext)
Finally, move the emptySquare(context) function into the mousemove event callback and edit it as follows:
function emptySquare(context) {
context.clearRect(0, 0, canvas.width, canvas.height)
}
So it will only clear the #myBoard canvas while #bg stays the same without needing to redraw it each time.
Example:
const bg = document.getElementById('bg')
const bgContext = bg.getContext('2d')
drawBoard(bgContext)
function getSquare(canvas, evt) {
var rect = canvas.getBoundingClientRect()
return {
x: 1 + (evt.clientX - rect.left) - ((evt.clientX - rect.left) % 10),
y: 1 + (evt.clientY - rect.top) - ((evt.clientY - rect.top) % 10),
}
}
function emptySquare(context) {
context.clearRect(0, 0, canvas.width, canvas.height)
}
function range(start, end) {
var ans = []
if (end > start) {
for (let i = start; i <= end; i += 10) {
ans.push(i)
}
} else {
for (let i = start; i >= end; i -= 10) {
ans.push(i)
}
}
return ans
}
function drawBoard(context) {
for (var x = 0.5; x < 20001; x += 10) {
context.moveTo(x, 0)
context.lineTo(x, 20000)
}
for (var y = 0.5; y < 20001; y += 10) {
context.moveTo(0, y)
context.lineTo(20000, y)
}
context.strokeStyle = '#ddd'
context.stroke()
}
function fillSquare(context, x, y) {
context.fillStyle = '#70B7B5'
context.fillRect(x, y, 9, 9)
}
var canvas = document.getElementById('myBoard')
var context = canvas.getContext('2d')
var isDrag = false
canvas.addEventListener('mousedown', function(evt) {
var mousePos = getSquare(canvas, evt)
isDrag = true
fillSquare(context, mousePos.x, mousePos.y)
previousPos = mousePos
}, false)
canvas.addEventListener('mousemove', function(evt) {
if (isDrag) {
var mousePos = getSquare(canvas, evt)
var x_dist = range(previousPos.x, mousePos.x)
var y_dist = range(previousPos.y, mousePos.y)
emptySquare(context)
for (x in x_dist) {
for (y in y_dist) {
fillSquare(context, x_dist[x], y_dist[y])
}
}
}
}, false)
canvas.addEventListener('mouseup', function(evt) {
if (isDrag) {
isDrag = false
}
}, false)
#bg {
position: absolute;
z-index: -1;
}
<div>
<canvas id="bg" width="1440" height="1200"></canvas>
<canvas id="myBoard" width="1440" height="1200"></canvas>
</div>

Related

disabling button when input field is empty not working in javascript

I am trying to disable my download button when the field is empty, when the user types the name only it should show. because without entering text also the user is able to download image. I have done the following code:
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<link rel="stylesheet" type="text/css" href="style.css">
<div class="container">
<div style="margin-top: 5%; " class="row">
<?php
require('db_config.php');
$id=$_GET['editid'];
$sql = "SELECT * FROM image_gallery where id='$id'";
$images = $mysqli->query($sql);
while($image = $images->fetch_assoc()){
?>
<div style="margin-left: 5%;" class="col-md-5"><canvas id="imageCanvas"></canvas></div>
<div style="margin-left: 2%; margin-top: 10%;" class="col-md-5 col-sm-8">
<div class="modal-content">
<div class="modal-header">
<h4 class="something"><span class="sims">Card Name: &nbsp</span>
<?php echo $image['title']; ?>
</h4>
<div class="modal-body">
<form method="post" action="" id="form_name">
<div class="row">
<div class="col-md-12">
<input class="lolan" type="text" id="name" placeholder="Full Name" required />
<!-- <label for="name" class="form__label">Full Name</label> -->
</div>
<div id="chumma" class="col-md-12">
<button id="download" type="submit" onclick="download_image()" name="button" value="Download" class="btn btn-primary">Download</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
<script type="text/javascript">
var text_title = "Heading";
var canvas = document.getElementById('imageCanvas');
var ctx = canvas.getContext('2d');
var img = new Image();
// img.crossOrigin = "anonymous";
window.addEventListener('load', DrawPlaceholder)
function DrawPlaceholder() {
img.onload = function() {
DrawOverlay(img);
DrawText(text_title);
DynamicText(img)
};
img.src = 'uploads/<?php echo $image['
image '];?>';
}
var canvas = document.getElementsByTagName('canvas')[0];
canvas.width = 500;
canvas.height = 500;
function DrawOverlay(img) {
ctx.drawImage(img, 0, 0, img.width, img.height, 0, 0, canvas.width, canvas.height);
ctx.fillStyle = 'rgba(230, 14, 14, 0)';
ctx.fillRect(0, 0, canvas.width, canvas.height);
}
function DrawText(text) {
ctx.fillStyle = "black";
ctx.textBaseline = 'middle';
ctx.font = "50px 'Montserrat'";
ctx.fillText(text, 150, 250);
}
function DynamicText(img) {
document.getElementById('name').addEventListener('keyup', function() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
DrawOverlay(img);
text_title = this.value;
DrawText(text_title);
});
}
function download_image() {
var canvas = document.getElementById("imageCanvas");
image = canvas.toDataURL("image/png").replace("image/png", "image/octet-stream");
var link = document.createElement('a');
link.download = "my-image.png";
link.href = image;
link.click();
}
</script>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
validate();
$('#name').change(validate);
});
function validate() {
if ($('#name').val().length > 0 && {
$("#download").prop("disabled", false);
}
else {
$("#download").prop("disabled", true);
}
}
</script>
<?php } ?>
but this is not making the button from disabling when the input is empty. can anyone please tell me what is wrong in my code. thanks in advance
Your code has some syntax errors and you should use keyup event:
$(document).ready(function() {
validate();
$('#name').keyup(validate);
});
function validate() {
if ($('#name').val().length > 0) {
$("#download").prop("disabled", false);
}
else {
$("#download").prop("disabled", true);
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="name">
<button id="download">Download</button>
I've noticed 2 things in your JavaScript code:
$('#name').change(validate); is triggered only when you exit (blur) the field.
Instead, you can use:
$('#name').keyup(validate);
There's a syntax error at:
if ($('#name').val().length > 0 && {
You should close the parenthesis like:
if ($('#name').val().length > 0 ) {
Hope this helps!

Score not incrementing

I am programming a simple game in javascript and when the user hovers on the given coordinates it's score increases. My problem is the score does not increment after 1.
var x = Math.floor(Math.random() * 500) + 150;
var y = Math.floor(Math.random() * 500) + 150;
document.getElementById("demo2").innerHTML = y;
document.getElementById("demo1").innerHTML = x;
//live tracking of coordinates
$("div.frame").mousemove(function (event) {
var xco = event.clientX;
var yco = event.clientY;
var xcoor = "X co-ords: " + xco;
var ycoor = "Y co-ords: " + yco;
document.getElementById("display1").innerHTML = xcoor;
document.getElementById("display2").innerHTML = ycoor;
//keeping score
if (xco == x && yco == y) {
count++;
console.log(count);
document.getElementById("score").innerHTML = count;
generate();
}
//Generating Co-ordinates
function generate() {
var x = Math.floor(Math.random() * 500) + 150;
var y = Math.floor(Math.random() * 500) + 150;
document.getElementById("demo2").innerHTML = y;
document.getElementById("demo1").innerHTML = x;
function points(x, y) {
if (xco == x && yco == y) {
count++;
console.log(count);
document.getElementById("score").innerHTML = count;
generate();
}
}
points(x, y);
}
})
Even after adding a global count variable, your code is not working properly because of your if (xco == x && yco == y) condition fails after first run. Here you are comparing randomly generated x and y with xco, yco and updating score and calling generate again.
On your generate function you are creating new local variable x and y, not updating the global x and y. And the subsequent comparison (xco == x && yco == y) will fail because it still using the old x and y.
On your generate function, updating the global x and y should fix this issue,
x = Math.floor(Math.random() * 500) + 150;
y = Math.floor(Math.random() * 500) + 150;
Here is the complete code, I also made some minor changes, removed some redundant and duplicate codes
// Code goes here
$(document).ready(function(){
//on clicking let's play
var t = 120;
var count = 0;
$("button.play").click(function(event){
event.preventDefault();
$(".fadeout").fadeOut(2000, function(){
$(".heading").text("Click on the Start button when you're ready");
});
$(".hidden").attr("hidden", false);
});
function start(){
//init game timer
var Timer = setInterval(function(){
document.getElementById("time1").innerHTML = t;
--t;
if(t < 0){
clearInterval(Timer);
document.getElementById("timeout").innerHTML = "Time's Up |";
$("div.frame").attr("hidden",true);
}
},1000);
var x = Math.floor(Math.random()*500)+150;
var y = Math.floor(Math.random()*500)+150;
document.getElementById("demo2").innerHTML = y;
document.getElementById("demo1").innerHTML = x;
//live tracking of coordinates
$("div.frame").mousemove(function(event){
var xco = event.clientX;
var yco = event.clientY;
var xcoor = "X co-ords: " + xco;
var ycoor = "Y co-ords: " + yco;
document.getElementById("display1").innerHTML = xcoor;
document.getElementById("display2").innerHTML = ycoor;
//keeping score
points(xco, yco);
})
$("div.frame").mouseout(function(event){
document.getElementById("display1").innerHTML = " ";
document.getElementById("display2").innerHTML = " ";
})
//Generating Co-ordinates
function generate(){
x = Math.floor(Math.random()*500) + 150;
y = Math.floor(Math.random()*500) + 150;
document.getElementById("demo2").innerHTML = y;
document.getElementById("demo1").innerHTML = x;
}
function points(xco, yco){
if(x == xco && y == yco){
count++;
console.log(count);
document.getElementById("score").innerHTML = count;
generate();
}
}
}
$("button.start").click(function(event){
event.preventDefault();
start();
$(this).fadeOut(1500);
$(this).attr("disabled",true);
$(".afterstart").fadeOut(1500);
});
});
/* Styles go here */
body{
height: 1200px;
background-size: cover;
}
.jumbotron{
margin-top: 250px;
padding: 20px;
height: 350px;
background-size: cover;
background-attachment: fixed;
}
.heading{
font-size: 30px;
margin-top: 100px;
}
.frame{
height: 1000px;
width: 1500px;
border: 10px solid black;
}
ul {
background: #40475A;
padding: 10px;
width: 100%;
}
.stats{
font-size: 30px;
margin-top: 80px;
}
.info{
font-size: 30px;
color:aliceblue;
}
.bold{
font-size: 25px;
color:antiquewhite;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
<title>Irritate</title>
</head>
<body>
<div>
<ul class="nav nav-pills pl-5 fixed-top d-flex justify-content-center" style="font-size: 25px">
<li class="nav-item">
<a class="nav-link" data-toggle="pill" id="display1"></a>
</li>
<li class="nav-item">
<a class="nav-link" id="display2"></a>
</li>
</ul>
</div>
<div class="jumbotron fadeout">
<div class="display-3 text-muted d-flex justify-content-center"> Hand-Job </div>
<p class="info"> All you have to do is try to match the co-ordinates that will display on the screen </p>
<p class="bold"><kbd>PS:</kbd>This game will test your patience</p>
<form>
<div class="input-group w-75">
<div class="input-group-prepend">
<span class="input-group-text">Name:</span>
</div>
<input type="text" class="form-control" value="">
<div class="input-group-append">
<button class="btn btn-outline-success play">Let's Play</button>
</div>
</div>
</form>
</div>
<div class="hidden" hidden="true">
<div>
<p class="text-danger heading afterstart"></p>
<button class="btn btn-danger w-25 start">Start</button>
<div class="d-flex d-flex-inline stats">
<p class="ml-3">X Co-ordinate:<span id="demo1" class="ml-2"></span><span> | </span></p>
<p class="ml-3">Y Co-ordinate:<span id="demo2" class="ml-2"></span><span> | </span></p>
<p class="ml-3">Time Left:<span id="time1" class="ml-2"></span> <span> | </span></p>
<p id="timeout" class="ml-3"></p>
<p>Score: <span id="score"></span></p>
</div>
</div>
<div class="frame ml-2">
</div>
<p id="result"></p>
</div>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin="anonymous"></script>
</body>
</html>
Here is plunker url for the above code https://plnkr.co/edit/7ia7MkMimzlsAxTCWAc9?p=preview
i think its because your count variable is local and only live in if block if you want to have count in other place please declare it as global variable
var x = Math.floor(Math.random() * 500) + 150;
var y = Math.floor(Math.random() * 500) + 150;
document.getElementById("demo2").innerHTML = y;
document.getElementById("demo1").innerHTML = x;
var count = 0;
//live tracking of coordinates
$("div.frame").mousemove(function (event) {
...
})

Fabric JS & proper collision detection

I am using the current version of Fabric JS (1.7.13) and I want some proper collision detection.
The Fabric JS website has this page: http://fabricjs.com/intersection
And there is a note at the top of the page:
Note that intersection is checked against bounding boxes, not actual
shapes
I am after a solution that does collision detection on the actual shapes.
Does such a solution exist?
I have found some similar questions here, like this one, but all of the ones I have found only do collision detection on the bounding boxes, not on the shapes themselves.
Maybe this code pen can help you- https://codepen.io/qbahamutp/pen/EPJmzj
/*
canvas dimension settings, using asset:
seiyria's bootstrap-slider
https://github.com/seiyria/bootstrap-slider
*/
var AdjustCanvasDimensions = function() {
window.canvas.setHeight(iHeight.getValue());
window.canvas.setWidth(iWidth.getValue());
window.canvas.renderAll();
$('label[for="canvas-width"]').text( iWidth.getValue() + 'cm' );
$('label[for="canvas-height"]').text( iHeight.getValue() + 'cm' );
console.log( 'Height:' + iHeight.getValue() );
// console.log( 'Width:' + iWidth.getValue() );
}
var iWidth = $('#canvas-width').slider().on('slide', AdjustCanvasDimensions).data('slider');
var iHeight= $("#canvas-height").slider({
// reversed : true
}).on('slide', AdjustCanvasDimensions).data('slider');
/*
canvas setup using asset:
fabricjs
https://github.com/kangax/fabric.js/
*/
window.canvas = new fabric.Canvas('fabriccanvas');
window.counter = 0;
var newleft = 0;
var edgedetection = 20; //pixels to snap
canvas.selection = false;
function plusrect(top, left, width, height, fill) {
window.canvas.add(new fabric.Rect({
top: 100,
name: 'rectangle ' + window.counter,
left: 0 + newleft,
width: 100,
height: 100,
fill: 'rgba(' + (Math.floor(Math.random() * 256)) + ',' + (Math.floor(Math.random() * 256)) + ',' + (Math.floor(Math.random() * 256)) + ', 0.75)',
lockRotation: true,
lockScalingX: true,
lockScalingY: true,
originX: 'left',
originY: 'top',
cornerSize: 15,
hasRotatingPoint: false,
perPixelTargetFind: true,
}));
window.counter++;
newleft += 200;
}
this.canvas.on('object:moving', function (e) {
var obj = e.target;
obj.setCoords(); //Sets corner position coordinates based on current angle, width and height
canvas.forEachObject(function (targ) {
activeObject = canvas.getActiveObject();
if (targ === activeObject) return;
if (Math.abs(activeObject.oCoords.tr.x - targ.oCoords.tl.x) < edgedetection) {
activeObject.left = targ.left - activeObject.width;
}
if (Math.abs(activeObject.oCoords.tl.x - targ.oCoords.tr.x) < edgedetection) {
activeObject.left = targ.left + targ.width;
}
if (Math.abs(activeObject.oCoords.br.y - targ.oCoords.tr.y) < edgedetection) {
activeObject.top = targ.top - activeObject.height;
}
if (Math.abs(targ.oCoords.br.y - activeObject.oCoords.tr.y) < edgedetection) {
activeObject.top = targ.top + targ.height;
}
if (activeObject.intersectsWithObject(targ) && targ.intersectsWithObject(activeObject)) {
targ.strokeWidth = 10;
targ.stroke = 'red';
} else {
targ.strokeWidth = 0;
targ.stroke = false;
}
if (!activeObject.intersectsWithObject(targ)) {
activeObject.strokeWidth = 0;
activeObject.stroke = false;
}
});
});
$('#pushit').on('click', function(){
plusrect()
});
<link href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.2.3/animate.min.css" rel="stylesheet"/>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet"/>
<link href="https://cdn.rawgit.com/seiyria/bootstrap-slider/master/dist/css/bootstrap-slider.min.css" rel="stylesheet"/>
<script src="https://rawgithub.com/kangax/fabric.js/master/dist/fabric.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdn.rawgit.com/seiyria/bootstrap-slider/master/dist/bootstrap-slider.min.js"></script>
<div id="start" class="container">
<form>
<fieldset>
<legend>Canvas eigenschappen</legend>
<div class="row">
<div class="form-group col-xs-9 col-xs-offset-2 col-md-offset-2">
<label for="canvas-width">Breedte</label>
<input id="canvas-width" name="canvas-width" data-slider-id='canvas-width' type="text" data-slider-min="100" data-slider-max="1000" data-slider-step="10" data-slider-value="500" style="width: 100%" />
</div>
</div>
<div class="row clearfix">
<div class="form-group col-xs-2 col-md-2 text-right">
<label for="canvas-height">Hoogte</label>
<input id="canvas-height" name="canvas-height" data-slider-id='canvas-height' type="text" data-slider-min="100" data-slider-max="400" data-slider-step="10" data-slider-value="200" data-slider-orientation="vertical" />
</div>
<div class="col-xs-9 canvaswrapper">
<canvas id="fabriccanvas" width="500" height="200" style="border:1px solid #ccc"></canvas>
</div>
</div>
<div class="row">
<div class="form-group col-xs-10">
<button type="button" id="pushit" class="btn btn-primary btn-lg">Object toevoegen </button>
</div>
</div>
</fieldset>
</form>
</div>

Draw More Arc Canvas

Hello People I'd Like to Know How to Draw More Arc Inside My Canvas, What I Need to Draw This circles:
So I Write This Responsive Code to Make my Canvas is Responsive:
var myCanvas = document.getElementById('myCanvas');
var ctx = myCanvas.getContext('2d');
var centerX = myCanvas.width / 2;
var centerY = myCanvas.height / 2;
var borderWidth = 20;
var borderColor = '#2DC36A';
var radius = (myCanvas.width / 2) - (borderWidth / 2);
// days arc canvas background
ctx.beginPath();
ctx.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
ctx.lineWidth = borderWidth;
ctx.strokeStyle = borderColor;
ctx.stroke();
ctx.closePath();
// Make Canvas Responsive
function makeResponsive() {
var containerWidth = $('.progress-nested').width();
$('.progress-nested').height(containerWidth);
var canvasElements = ['#myCanvas'];
$('#myCanvas').width(containerWidth).height(containerWidth);
}
makeResponsive(); // Make Canvas Responsive in Document ready
$(window).resize(function () {
makeResponsive(); // Make Canvas Responsive in Window Resize
});
#progress {
width: 100%;
padding: 5px;
}
.progress-nested{
position:relative;
border-radius:50%;
}
canvas {
display:block;
position:absolute;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<div id="progress">
<div class="container">
<div class="row">
<div class="col-xs-3 col-md-2 col-md-offset-2">
<div class="progress-nested">
<canvas id="myCanvas" width="250" height="250"></canvas>
</div>
</div>
</div>
</div>
</div>
Note: Please Run Code Snippet In Full Page

Conditonally draw HTML5 canvas

So to stay trained during the summer holliday I decided I wanted to convert an existing windows forms application into a web api application.
With the tool I am trying to make you can make UML use cases and diagrams. I decided to use HTML5 canvas, Javascript and bootstrap to do the job.
The issue I'm having is that the actors should be drawn one at a time when a radiobutton is checked but when I try to do this condtionally it prints three actors when the document is ready instead of wating untill the 2 radiobuttons are checked.
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<link rel="stylesheet" href="css/bootstrap.min.css">
<link rel="stylesheet" href="css/styles.css">
<script src="js/jquery-1.10.2.min.js"></script>
<script src="https://www.atlasestateagents.co.uk/javascript/tether.min.js"></script><!-- Tether for Bootstrap -->
<script src="js/bootstrap.min.js"></script>
<script src="js/drawfigure.js"></script>
<body>
<div class="container">
<div class="col-md-4">
<fieldset id="group1">
<h2>Elementen</h2>
<div class="radio">
<label class="radio-inline"><input type="radio" value="Actor" id="rbActor" name="optradioElementen">Actor</label>
</div>
<div class="radio">
<label class="radio radio-inline"><input type="radio" id="rbLine" value="Line" name="optradioElementen">Line</label>
</div>
<div class="radio">
<label class="radio radio-inline"><input type="radio" id="UseCase" value="UseCase" name="optradioElementen">Use Case</label>
</div>
</fieldset>
</div>
<div class="col-md-4">
<fieldset>
<div>
<h2>Modes</h2>
<div class="radio">
<label class="radio control-label"><input type="radio" value="Create" id="rbCreate"
name="optradioModes">Create</label>
</div>
<div class="radio">
<label class="radio control-label"><input type="radio" value="Select" id="rbSelect"
name="optradioModes">Select</label>
</div>
</div>
</fieldset>
</div>
<div class="col-md-2 col-md-offset-2">
<h2>verwijderen</h2>
<button class="btn btn-default">Clear All</button>
<button class="btn btn-default">Remove</button>
</div>
</div>
<div class="container" style="position:relative;">
<canvas id="thecanvas" width="800" height="800">
</canvas>
</div>
<!--myModal-->
<div class="modal" tabindex="-1" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="false">×</span></button>
<h4 class="modal-title">Modal title</h4>
</div>
<div class="modal-body">
<form>
<fieldset class="form-group">
<label for="exampleInputEmail1">Email address</label>
<input type="email" class="form-control" id="exampleInputEmail1" placeholder="Enter email">
<small class="text-muted">We'll never share your email with anyone else.</small>
</fieldset>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div>
<!-- /.modal -->
</body>
</html>
and this is my javascript / jquery
$(document).ready(function() {
var canvas = document.getElementById("thecanvas");
var ctx = canvas.getContext('2d');
function drawEllipseOnPosition(event) {
var x = event.x - 400;
var y = event.y - 150;
drawEllipseWithBezierByCenter(ctx, x, y, 200, 60, '#0099ff', "Jeff");
}
function drawActor(startX, startY) {
if (canvas.getContext("2d")) { // Check HTML5 canvas support
context = canvas.getContext("2d"); // get Canvas Context object
context.beginPath();
context.fillStyle = "bisque"; // #ffe4c4
context.arc(startX, startY, 30, 0, Math.PI * 2, true); // draw circle for head
// (x,y) center, radius, start angle, end angle, anticlockwise
context.fill();
context.beginPath();
context.strokeStyle = "red"; // color
context.lineWidth = 3;
context.arc(startX, startY, 20, 0, Math.PI, false); // draw semicircle for smiling
context.stroke();
// eyes
context.beginPath();
context.fillStyle = "green"; // color
context.arc(startX - 10, startY - 5, 3, 0, Math.PI * 2, true); // draw left eye
context.fill();
context.arc(startX + 10, startY - 5, 3, 0, Math.PI * 2, true); // draw right eye
context.fill();
// body
context.beginPath();
context.moveTo(startX, startY + 30);
context.lineTo(startX, startY + 130);
context.strokeStyle = "navy";
context.stroke();
// arms
context.beginPath();
context.strokeStyle = "#0000ff"; // blue
context.moveTo(startX, startY + 30);
context.lineTo(startX - 50, startY + 80);
context.moveTo(startX, startY + 30);
context.lineTo(startX + 50, startY + 80);
context.stroke();
// legs
context.beginPath();
context.strokeStyle = "orange";
context.moveTo(startX, startY + 130);
context.lineTo(startX - 50, startY + 230);
context.moveTo(startX, startY + 130);
context.lineTo(startX + 50, startY + 230);
context.stroke();
}
}
function drawEllipseWithBezierByCenter(ctx, cx, cy, w, h, style, text) {
drawEllipseWithBezier(ctx, cx - w / 2.0, cy - h / 2.0, w, h, style, text);
}
function drawEllipseWithBezier(ctx, x, y, w, h, style, text) {
var kappa = .5522848,
ox = (w / 2) * kappa, // control point offset horizontal
oy = (h / 2) * kappa, // control point offset vertical
xe = x + w, // x-end
ye = y + h, // y-end
xm = x + w / 2, // x-middle
ym = y + h / 2; // y-middle
ctx.save();
ctx.beginPath();
ctx.moveTo(x, ym);
ctx.bezierCurveTo(x, ym - oy, xm - ox, y, xm, y);
ctx.bezierCurveTo(xm + ox, y, xe, ym - oy, xe, ym);
ctx.bezierCurveTo(xe, ym + oy, xm + ox, ye, xm, ye);
ctx.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym);
ctx.font = '20pt Calibri';
ctx.fillText(text, x + 25, y + 35);
if (style)
ctx.strokeStyle = style;
ctx.stroke();
ctx.restore();
}
canvas.addEventListener("click", drawEllipseOnPosition, false);
var i = 0;
if($("input[value='Actor']").is(":checked")){
if($("input[value='Create']:checked"){
while(i < 3){
if(i==0){
drawActor(100, 550);
}
if(i == 1){
drawActor(100, 300);
}
if( i == 2){
drawActor(100, 50);
}
i++;
}
}
}
});
Any help would be very much appreciated!
You can "jump out" of a loop using break.
var i = 0;
if ($("input[value='Actor']").is(":checked") && $("input[value='Create']:checked")) {
while (i < 3) {
if (i == 0) {
drawActor(100, 550);
break;
}
if (i == 1) {
drawActor(100, 300);
break;
}
if (i == 2) {
drawActor(100, 50);
break;
}
i++;
}
}

Categories