Drawing circle and squares with radio buttons not working - javascript

my question today is to ask why when I switch radio buttons, drawing a circle and drawing a square don't work. This is for my paint program im creating. Please help me with this question. Also can you help why the program is so laggy? XD. The code is down here:
var square = true
function myFunction() {
var x = document.getElementById("myColor").value;
ctx.fillStyle = x;
};
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var size = 5
var eraserSize = 5;
$('#colorForm input').on('change', function() {
ctx.fillStyle = $(this).val();
});
$('#sizeForm input').on('change', function() {
size = $(this).val();
});
function drawRect(event) {
var posX = event.pageX - $("#canvas").offset().left - 4
var posY = event.pageY - $("#canvas").offset().top - 4
ctx.fillRect(posX, posY, size, size)
}
function drawCircle(event) {
var posX = event.pageX - $("#canvas").offset().left
var posY = event.pageY - $("#canvas").offset().top
ctx.beginPath();
ctx.arc(posX, posY, size - 1, 0, Math.PI / 2, false);
ctx.closePath();
ctx.fill();
}
function check() {
if (square === true) {
$("html").mousedown(function() {
$("html").mousemove(function(event) {
drawRect(event);
})
$("html").click(function(event) {
drawRect(event);
})
})
$("html").mouseup(function() {
$("html").off("mousemove")
})
}
if (square === false) {
$("html").mousedown(function() {
$("html").mousemove(function(event) {
drawCircle(event);
})
$("html").click(function(event) {
drawCircle(event);
})
})
$("html").mouseup(function() {
$("html").off("mousemove")
})
}
}
function clearCanvas() {
if (confirm("Are you sure you want to clear your drawing?") == true) {
ctx.clearRect(0, 0, 800, 800)
}
}
setInterval(function() {
check();
}, 1)
#canvas {
border: 1px solid black
}
<p id="demo"></p>
<script src="https://code.jquery.com/jquery-2.1.0.js"></script>
<canvas id="canvas" width="800" height="800" style="cursor:crosshair"></canvas>
<br />
<STRONG>Choose your drawing shape</STRONG>:
<input type="radio" name="shape" onclick="square = true" checked="checked">Square
<input type="radio" name="shape" onclick="square = false">Circle
<br />
<STRONG>Color Settings</STRONG>:
<input type="color" id="myColor">
<button onclick="myFunction()">OK</button>
<br />Basic Colours:
<br />
<form id="colorForm">
<input type="radio" name="color" value="black" checked="checked">Black
<input type="radio" name="color" value="red">Red
<input type="radio" name="color" value="orange">Orange
<input type="radio" name="color" value="yellow">Yellow
<input type="radio" name="color" value="green">Green
<input type="radio" name="color" value="blue">Blue
<input type="radio" name="color" value="purple">Purple
<input type="radio" name="color" value="white">Eraser (White)
</form>
<form id="sizeForm">
<br />
<STRONG>Size</STRONG>:
<input type="radio" name="size" value="10">Big
<input type="radio" name="size" value="5" checked="checked">Normal
<input type="radio" name="size" value="2">Small
</form>
<br />
<button onclick="clearCanvas()">Clear Drawing</button>

.arc() takes radians - 2π is a full circle, you are doing π/2 which is 90 degrees. Here's an easy converter: http://www.rapidtables.com/convert/number/radians-to-degrees.htm.
I adjusted your code below, you were not cleaning up the onmousedown listener. The click listener is actually unnecessary, if a mouseup is used instead (since you're already mousedown, you have half of the click already). The setInterval was unnecessary; you can listen for mousedown to start drawing. Limiting the scope of the listeners to the canvas vs. all of the HTML can improve performance also.
var square = true; // Set
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var size = 5
var eraserSize = 5;
$('#colorForm input, #myColor').on('change', function() {
ctx.fillStyle = $(this).val();
});
$('#sizeForm input').on('change', function() {
size = $(this).val();
});
function drawRect(event) {
var posX = event.pageX - $(canvas).offset().left - 4
var posY = event.pageY - $(canvas).offset().top - 4
ctx.fillRect(posX, posY, size, size)
}
function drawCircle(event) {
var posX = event.pageX - $(canvas).offset().left
var posY = event.pageY - $(canvas).offset().top
ctx.beginPath();
ctx.arc(posX, posY, size - 1, 0, Math.PI * 2, false);
ctx.closePath();
ctx.fill();
}
function mouseDown(e) {
// We only care about mousemove on the canvas, not the whole page
if (square) {
$(canvas).on('mousemove', drawRect).on('mouseup', drawRect);
} else {
$(canvas).on('mousemove', drawCircle).on('mouseup', drawCircle);
}
// If the user mouseup outside of the canvas, we don't want to keep listening, so listen for mouseup on the whole page to remove our other drawing listeners
$('html').one('mouseup', function() { // "one" means that it will only fire once and will stop listening after that (cleanup for free)
$(canvas).off('mousemove').off('mouseup');
});
}
function clearCanvas() {
if (confirm("Are you sure you want to clear your drawing?") == true) {
ctx.clearRect(0, 0, 800, 800)
}
}
// We only care about mousedown on the canvas, not the whole page
$(canvas).on('mousedown', mouseDown);
#canvas {
border: 1px solid black;
cursor: crosshair;
}
h2,
h3 {
margin-bottom: 0;
}
h2 {
font-size: 1.1rem;
}
h3 {
font-size: 1rem;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<canvas id="canvas" width="300" height="200"></canvas>
<h2>Choose your drawing shape:</h2>
<p>
<input type="radio" name="shape" onclick="square=true;" checked="checked">Square
<input type="radio" name="shape" onclick="square=false;">Circle
</p>
<h2>Color Settings:</h2>
<input type="color" id="myColor" />
<form id="colorForm">
<h3>Basic Colours:</h3>
<p>
<input type="radio" name="color" value="black" checked="checked" />Black
<input type="radio" name="color" value="red" />Red
<input type="radio" name="color" value="orange" />Orange
<input type="radio" name="color" value="yellow" />Yellow
<input type="radio" name="color" value="green" />Green
<input type="radio" name="color" value="blue" />Blue
<input type="radio" name="color" value="purple" />Purple
<input type="radio" name="color" value="white" />Eraser (White)
</p>
</form>
<form id="sizeForm">
<h2>Size:</h2>
<p>
<input type="radio" name="size" value="10" />Big
<input type="radio" name="size" value="5" checked="checked" />Normal
<input type="radio" name="size" value="2" />Small
</p>
</form>
<br />
<button onclick="clearCanvas()">Clear Drawing</button>

First of all, your code is missing a ton of semi-colons at the end of lines, which is VERY bad practice in general. I'd say your first line of action is to fill those in to make sure missing semi-colons is causing the issue.
Second, when you are changing the square variable, it is first assigning the onmousedown handler to use the drawRect method. However, when you select circle and square becomes false, you are then assigning the onmousedown handler to use the drawCircle method without unbinding the previous onmousedown handler. With jQuery, assigning a handler again does not overwrite the previous handler.
Another issue I see with this is that the circle is not being drawn correctly in the first place. If you set square=false initially and try to draw a circle, it is only drawing a semi-circle, so check your drawCircle.

Related

Issue when trying to change font size and color in canvas

I'm trying to change my font size and color in my canvas on a photo. So you have to upload a photo before you're able to add text to the image. After you add the photo and add text, then you're able to change the color and font, but when trying to do so you have to re-submit or the changes are not applied. Any ideas on what is happening? Do I have to re-draw it when they change colors or font sizes? Thanks In advance.
HTML:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<input id="theText" type="text">
<button id="submit">Draw text on canvas</button>
<br>
<canvas id="canvas" width="1000" height="500" class="playable-canvas"></canvas>
<div id="image_div">
<h1> Choose an Image to Upload </h1>
<input type='file' name='img' id='uploadimage' />
</div>
<div class="playable-buttons">
  <input id="edit" type="button" value="Edit" />
  <input id="reset" type="button" value="Reset" />
</div>
<textarea id="code" class="playable-code">
ctx.filter = 'blur(0px)';
</textarea>
<!-- Change Font Size -->
<div class="radio">
<input type="radio" name="radio" id="size16" onclick="size16()" checked="">
<label for="size16"> Font Size 16 </label>
</div>
<div class="radio">
<input type="radio" name="radio" id="size20" onclick="size20()" >
<label for="size20"> Font Size 20 </label>
</div>
<div class="radio">
<input type="radio" name="radio" id="size25" onclick="size25()" >
<label for="size25"> Font Size 25 </label>
</div>
<div class="radio">
<input type="radio" name="radio"id="size30" onclick="size30()" >
<label for="size30"> Font Size 30</label>
</div>
<div class="radio">
<input type="radio" name="radio" id="size35" onclick="size35()" >
<label for="size35"> Font Size 35 </label>
</div>
<div class="radio">
<input type="radio" name="radio" id="size40" onclick="size40()" >
<label for="size40"> Font Size 40 </label>
</div>
<div class="radio">
<input type="radio" name="radio" id="size45" onclick="siz45()" >
<label for="size45"> Font Size 45 </label>
</div>
<div class="radio">
<input type="radio" name="radio" id="size50" onclick="size50()" >
<label for="size50"> Font Size 50 </label>
</div>
<Br>
<!-- Change Color on Text -->
<div class="col-lg-2 col-md-2 col-xs-12">
<div class="radio">
<input type="radio" name="radio" id="black" onclick="BlackText()" checked="">
<label for="radio1"> Black </label>
</div>
<div class="radio">
<input type="radio" name="radio" id="white" onclick="WhiteText()" >
<label for="radio1"> White </label>
</div>
<div class="radio">
<input type="radio" name="radio" id="yellow" onclick="YellowText()" >
<label for="radio1"> Yellow </label>
</div>
<div class="radio radio-primary">
<input type="radio" name="radio" id="blue" onclick="BlueText()" >
<label for="radio3"> Blue </label>
</div>
<div class="radio radio-success">
<input type="radio" name="radio" id="green" onclick="GreenText()" >
<label for="radio4"> Green </label>
</div>
<div class="radio radio-danger">
<input type="radio" name="radio"id="red" onclick="RedText()" >
<label for="radio6"> Red </label>
</div>
<div class="radio radio-warning">
<input type="radio" name="radio" id="orange" onclick="OrangeText()" >
<label for="radio7"> Orange </label>
</div>
<div class="radio radio-purple">
<input type="radio" name="radio"id="purple" onclick="PurpleText()" >
<label for="radio8"> Purple </label>
</div>
</div>
Javscript:
//===========================================================================================================================
// Javascript that loads Image into canvas
//===========================================================================================================================
var drawnImage;
function drawImage(ev) {
console.log(ev);
var ctx = document.getElementById('canvas').getContext('2d'),
img = new Image(),
f = document.getElementById("uploadimage").files[0],
url = window.URL || window.webkitURL,
src = url.createObjectURL(f);
img.src = src;
img.onload = function() {
drawnImage = img;
ctx.drawImage(img, 0, 0);
url.revokeObjectURL(src);
}
}
document.getElementById("uploadimage").addEventListener("change", drawImage, false);
//===========================================================================================================================
// Javascript for input in textbox
//===========================================================================================================================
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
var textarea = document.getElementById('code');
var reset = document.getElementById('reset');
var edit = document.getElementById('edit');
var code = textarea.value;
function drawCanvas() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
eval(textarea.value);
drawImage();
}
reset.addEventListener('click', function() {
textarea.value = code;
drawCanvas();
});
edit.addEventListener('click', function() {
textarea.focus();
})
textarea.addEventListener('input', drawCanvas);
window.addEventListener('load', drawCanvas);
//===========================================================================================================================
// Javascript for Moving Text around.
//===========================================================================================================================
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var $canvas = $("#canvas");
var canvasOffset = $canvas.offset();
var offsetX = canvasOffset.left;
var offsetY = canvasOffset.top;
var scrollX = $canvas.scrollLeft();
var scrollY = $canvas.scrollTop();
var startX;
var startY;
var texts = [];
var selectedText = -1;
function draw() {
ctx.rect(0, 0, canvas.width, canvas.height);
for (var i = 0; i < texts.length; i++) {
var text = texts[i];
// ctx.fillStyle = "blue";
ctx.fillText(text.text, text.x, text.y);
}
}
function redraw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.drawImage(drawnImage, 0, 0);
draw();
}
function textHittest(x, y, textIndex) {
var text = texts[textIndex];
return (x >= text.x && x <= text.x + text.width && y >= text.y - text.height && y <= text.y);
}
function handleMouseDown(e) {
e.preventDefault();
startX = parseInt(e.clientX - offsetX);
startY = parseInt(e.clientY - offsetY);
for (var i = 0; i < texts.length; i++) {
if (textHittest(startX, startY, i)) {
selectedText = i;
}
}
}
function handleMouseUp(e) {
e.preventDefault();
selectedText = -1;
}
function handleMouseOut(e) {
e.preventDefault();
selectedText = -1;
}
function handleMouseMove(e) {
if (selectedText < 0) {
return;
}
e.preventDefault();
mouseX = parseInt(e.clientX - offsetX);
mouseY = parseInt(e.clientY - offsetY);
var dx = mouseX - startX;
var dy = mouseY - startY;
startX = mouseX;
startY = mouseY;
var text = texts[selectedText];
text.x += dx;
text.y += dy;
redraw();
}
$("#canvas").mousedown(function(e) {
handleMouseDown(e);
});
$("#canvas").mousemove(function(e) {
handleMouseMove(e);
});
$("#canvas").mouseup(function(e) {
handleMouseUp(e);
});
$("#canvas").mouseout(function(e) {
handleMouseOut(e);
});
$("#submit").click(function() {
var y = texts.length * 20 + 20;
var text = {
text: $("#theText").val(),
x: 20,
y: y
};
// ctx.font = "16px verdana";
text.width = ctx.measureText(text.text).width;
text.height = 16;
texts.push(text);
draw();
});
//===========================================================================================================================
// Javascript for Text Size :)
//===========================================================================================================================
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
function size16 () {
ctx.font = "16px verdana";
}
function size20 () {
ctx.font = "20px verdana";
}
function size25 () {
ctx.font = "25px verdana";
}
function size30 () {
ctx.font = "30px verdana";
}
function size35 () {
ctx.font = "35px verdana";
}
function size40 () {
ctx.font = "40px verdana";
}
function size45 () {
ctx.font = "45px verdana";
}
function size50 () {
ctx.font = "50px verdana";
}
//===========================================================================================================================
// Javascript for Drop down for Text Color :)
//===========================================================================================================================
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
function PurpleText () {
ctx.fillStyle= 'purple';
}
function BlackText () {
ctx.fillStyle= 'black';
}
function YellowText () {
ctx.fillStyle= 'yellow';
}
function OrangeText () {
ctx.fillStyle = "orange";
}
function BlueText () {
ctx.fillStyle= 'blue';
}
function WhiteText () {
ctx.fillStyle = "white";
}
function GreenText () {
ctx.fillStyle= 'green';
}
function RedText () {
ctx.fillStyle = "red";
}
You have either to draw again the canvans or draw (refresh) it continuosly every xxx milliseconds.

Javascript / jQuery UI: Changing element img src from an array of images based on current img src

I have a canvas element containing an image, which is initially a Green Square. I'm trying to change the displayed image based on the input from two sets of jQuery UI radio buttons: the first set allows the user to select a colour and has 3 options (Red/Green/Blue), and the second set allows the user to select a shape (Circle/Square).
My Javascript code declares an array of images, one of which is then assigned to display in the canvas element when a button option is checked, like so:
var images = new Array();
images[0] = new Image();
images[0].src = '../../../media/images/Red-Circle.png';
images[1] = new Image();
images[1].src = '../../../media/images/Red-Square.png';
images[2] = new Image();
images[2].src = '../../../media/images/Green-Circle.png';
images[3] = new Image();
images[3].src = '../../../media/images/Green-Square.png';
images[4] = new Image();
images[4].src = '../../../media/images/Blue-Circle.png';
images[5] = new Image();
images[5].src = '../../../media/images/Blue-Square.png';
$(function () {
$("#colour").buttonset();
$("#shape").buttonset();
});
$('#red').click(function () {
if ($('#red').is(':checked')) {
$("#container #image img").attr("src", images[1].src);
}
});
$('#green').click(function () {
if ($('#green').is(':checked')) {
$("#container #image img").attr("src", images[3].src);
}
});
$('#blue').click(function () {
if ($('#blue').is(':checked')) {
$("#container #image img").attr("src", images[5].src);
}
});
HTML:
<div id="container">
<div id="image">
<img src="media/images/Green-Square.png" />
</div>
</div>
<form>
<div id="colour">
<input type="radio" id="red" name="radio">
<label for="colour1">Red</label>
<input type="radio" id="green" name="radio" checked="checked">
<label for="colour2">Green</label>
<input type="radio" id="blue" name="radio">
<label for="colour3">Blue</label>
</div>
</form>
<form>
<div id="shape">
<input type="radio" id="circle" name="radio">
<label for="circle">Circle</label>
<input type="radio" id="square" name="radio" checked="checked">
<label for="square">Square</label>
</div>
</form>
I've only got as far as being able to select the colour. When it comes to selecting the shape, I want to change the displayed image to retain the previous choice of colour (so that for example, if Red was the currently selected colour and the user then selected Circle, the image displayed would change to a Red Circle and not a Green or Blue Circle). Conversely, if the user selected the shape first and THEN selected a colour, I want the displayed image to retain the choice of shape.
I have a vague idea that the solution might be to do with adding 1 or subtracting 1 from the array index based on what the current index is - but I have no clue how to implement this. I'm relatively new to JS so any help would be appreciated. Thanks.
You can store your images in an 'images' object and access them by string (ex images["RedSquare"]) I've put together a fiddle. The image links are broken but if you inspect the page you can see the src is being changed properly.
https://jsfiddle.net/5wv5ym5p/
HTML:
<div id="container">
<div id="image">
<img src="media/images/Green-Square.png" />
</div>
</div>
<form>
<div class="shape-config" id="colour">
<input type="radio" id="red" name="radio">
<label for="red">Red</label>
<input type="radio" id="green" name="radio" checked="checked">
<label for="green">Green</label>
<input type="radio" id="blue" name="radio">
<label for="blue">Blue</label>
</div>
</form>
<form>
<div class="shape-config" id="shape">
<input type="radio" id="circle" name="radio">
<label for="circle">Circle</label>
<input type="radio" id="square" name="radio" checked="checked">
<label for="square">Square</label>
</div>
</form>
JS (needs JQuery):
var images = {};
images["RedCircle"] = new Image();
images["RedCircle"].src = '../../../media/images/Red-Circle.png';
images["RedSquare"] = new Image();
images["RedSquare"].src = '../../../media/images/Red-Square.png';
images["GreenCircle"] = new Image();
images["GreenCircle"].src = '../../../media/images/Green-Circle.png';
images["GreenSquare"] = new Image();
images["GreenSquare"].src = '../../../media/images/Green-Square.png';
images["BlueCircle"] = new Image();
images["BlueCircle"].src = '../../../media/images/Blue-Circle.png';
images["BlueSquare"] = new Image();
images["BlueSquare"].src = '../../../media/images/Blue-Square.png';
$(function () {
$("#colour").buttonset();
$("#shape").buttonset();
});
$('.shape-config input').click(function () {
var colourId = $("#colour input:checked").attr("id");
var colour = $('label[for='+colourId+']').text();
var shapeId = $("#shape input:checked").attr("id");
var shape = $('label[for='+shapeId+']').text();
$("#container #image img").attr("src", images[colour+""+shape].src);
});
Here is an plunker for what you are trying to do.
https://plnkr.co/edit/jMvjJCxHZzr9dxw5B6RR?p=preview
the function you will require are
$('#circle').change(function () {
if ($('#circle').is(':checked')) {
var a = jQuery.grep(images, function( n ,i) {
if ( n.src == $("#container #image img").attr("src") )
return i;
})[0];
var index = images.indexOf(a);
$("#container #image img").attr("src", images[index-1].src);
}
});
$('#square').change(function () {
if ($('#square').is(':checked')) {
var a = jQuery.grep(images, function( n ,i) {
if ( n.src == $("#container #image img").attr("src") )
return i;
})[0];
var index = images.indexOf(a);
$("#container #image img").attr("src", images[index+1].src);
}
The color select button logic is not correct as well please use this logic there as well.
Why bother using arrays/indexes and storing it at all?
https://jsfiddle.net/0Lqgc3vx/
HTML
<img id="img" src="Green-Square.png" />
<form>
<input type="radio" name="colour" value="Red">
<label for="colour1">Red</label>
<input type="radio" name="colour" value="Green" checked="checked">
<label for="colour2">Green</label>
<input type="radio" name="colour" value="Blue">
<label for="colour3">Blue</label>
</form>
<form>
<input type="radio" name="shape" value="Circle">
<label for="circle">Circle</label>
<input type="radio" name="shape" value="Square" checked="checked">
<label for="square">Square</label>
</form>
JS
$("input[name='colour']").change(function () {
$("#img").attr("src", this.value + "-" + $("input[name='shape']:checked").val() + ".png");
});
$("input[name='shape']").change(function () {
$("#img").attr("src", $("input[name='colour']:checked").val() + "-" + this.value + ".png");
});

Drawing squares and drawing circles with radio buttons not working

My question today is to ask why when i switch radio buttons, drawing a circle doesn't work. Im creating a paint program. Please help me with this question.
Html:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<canvas id="canvas" width="300" height="200"></canvas>
<h2>Choose your drawing shape:</h2>
<p>
<input type="radio" name="shape" onclick="square=true;" checked="checked">Square
<input type="radio" name="shape" onclick="square=false;">Circle
</p>
<h2>Color Settings:</h2>
<input type="color" id="myColor" />
<form id="colorForm">
<h3>Basic Colours:</h3>
<p>
<input type="radio" name="color" value="black" checked="checked" />Black
<input type="radio" name="color" value="red" />Red
<input type="radio" name="color" value="orange" />Orange
<input type="radio" name="color" value="yellow" />Yellow
<input type="radio" name="color" value="green" />Green
<input type="radio" name="color" value="blue" />Blue
<input type="radio" name="color" value="purple" />Purple
<input type="radio" name="color" value="white" />Eraser (White)
</p>
</form>
<form id="sizeForm">
<h2>Size:</h2>
<p>
<input type="radio" name="size" value="10" />Big
<input type="radio" name="size" value="5" checked="checked" />Normal
<input type="radio" name="size" value="2" />Small
</p>
</form>
<button onclick="clearCanvas()">Clear Drawing</button>
Css:
#canvas {
border: 1px solid black;
cursor: crosshair;
}
h2,
h3 {
margin-bottom: 0;
}
h2 {
font-size: 1.1rem;
}
h3 {
font-size: 1rem;
}
And javascript:
var square = true; // Set
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var size = 5
var eraserSize = 5;
$('#colorForm input, #myColor').on('change', function() {
ctx.fillStyle = $(this).val();
});
$('#sizeForm input').on('change', function() {
size = $(this).val();
});
var drawRect = function (event) {
var posX = event.pageX - $(canvas).offset().left - 4
var posY = event.pageY - $(canvas).offset().top - 4
ctx.fillRect(posX, posY, size, size)
}
var drawCircle = function (event) {
var posX = event.pageX - $(canvas).offset().left
var posY = event.pageY - $(canvas).offset().top
ctx.beginPath();
ctx.arc(posX, posY, size - 1, 0, Math.PI * 2, false);
ctx.closePath();
ctx.fill();
}
function mouseDown(e) {
// We only care about mousemove on the canvas, not the whole page
if (square) {
$(canvas).on('mousemove', drawRect).on('mouseup', drawRect);
} else {
$(canvas).on('mousemove', drawCircle).on('mouseup', drawCircle);
}
// If the user mouseup outside of the canvas, we don't want to keep listening, so listen for mouseup on the whole page to remove our other drawing listeners
$('html').one('mouseup', function() { // "one" means that it will only fire once and will stop listening after that (cleanup for free)
$(canvas).off('mousemove').off('mouseup');
});
}
function clearCanvas() {
if (confirm("Are you sure you want to clear your drawing?") == true) {
ctx.clearRect(0, 0, 300, 300)
}
}
// We only care about mousedown on the canvas, not the whole page
$(canvas).on('mousedown', mouseDown);
Please help me with this question. Thanks for your support!!!

make a for-loop of several js functions

i have several js functions doing the same thing width different values for different divs. Here is the HTML-code:
<input id="kunst_radio1" type="radio" name="kunstmuseum" value="0" checked="checked" onClick="animateKunst('null')"><label for="kunst_radio1"></label>
<input id="kunst_radio2" type="radio" name="kunstmuseum" value="6794200" onClick="animateKunst('halb')"><label for="kunst_radio2"></label>
<input id="kunst_radio3" type="radio" name="kunstmuseum" value="13588400" onClick="animateKunst('voll')"><label for="kunst_radio3"></label>
<input id="hist_radio1" type="radio" name="hist" checked="checked" onClick="animateHist('null')"><label for="hist_radio1"></label>
<input id="hist_radio2" type="radio" name="hist" onClick="animateHist('halb')"><label for="hist_radio2"></label>
<input id="hist_radio3" type="radio" name="hist" onClick="animateHist('voll')"><label for="hist_radio3"></label>
I have about 15 radio button groups and for each group I have to execute this function with different values:
function animateKunst(val) {
var div = $('#kunstmuseum');
if(div.data('originalWidth') == undefined)
div.data('originalWidth', div.width());
var width = div.data('originalWidth');
if (val=="voll")
width *= .6;
else if (val=="halb")
width *= .8;
$('#kunstmuseum').animate({width: width}, 500);
}
function animateHist(val) {
var div = $('#historisch');
if(div.data('originalWidth') == undefined)
div.data('originalWidth', div.width());
var width = div.data('originalWidth');
if (val=="voll")
width *= .7;
else if (val=="halb")
width *= .9;
$('#historisch').animate({width: width}, 500);
}
Can I put all the values in an array and then make a for-loop? How can I do that?
I would slightly modify the ids so that I can reuse them more easily inside my function and define a mapping for your widths.
<script type="text/javascript">
var mapping = {
kunst: {
voll: 0.6,
halb: 0.8
},
hist: {
voll: 0.7,
halb: 0.9
},
null: {
voll: 0,
halb: 0
}
};
function animate(type, val) {
var div = $('#' + type);
if ( !div.data('originalWidth') ) {
div.data('originalWidth', div.width());
}
var width = div.data('originalWidth');
width *= mapping[type][val];
div.animate({ width: width }, 500);
}
</script>
<input id="kunst_radio1" type="radio" name="kunst" value="0" checked="checked"
onClick="animate('kunst', 'null')">
<label for="kunst_radio1"></label>
<input id="kunst_radio2" type="radio" name="kunst" value="6794200"
onClick="animate('kunst', 'halb')">
<label for="kunst_radio2"></label>
<input id="kunst_radio3" type="radio" name="kunst" value="13588400"
onClick="animate('kunst', 'voll')">
<label for="kunst_radio3"></label>
<input id="hist_radio1" type="radio" name="hist" checked="checked"
onClick="animate('hist', 'null')">
<label for="hist_radio1"></label>
<input id="hist_radio2" type="radio" name="hist"
onClick="animate('hist', 'halb')">
<label for="hist_radio2"></label>
<input id="hist_radio3" type="radio" name="hist"
onClick="animate('hist', 'voll')">
<label for="hist_radio3"></label>

Setting CSS Properties Dynamically

So I'm having an issue. I have to design a css button that can be customized by a user on the fly, with a few customization options. They have to be able to add text, change the button colour, change the button size and change how round the borders are. The thing is, my javascript functions to change the borders and the size of the button aren't working. They also make the other functions not work, oddly enough.
I was told to avoid using jQuery.
The Javascript for the size changing function:
function aBc()
{
var a = document.getElementById("buttontest");
if(document.getElementById("smallS").checked)
{
a.style.width = 100px;
}
else if(document.getElementById("mediumS").checked)
{
a.style.width = 150px;
}
else if(document.getElementById("largeS").checked)
{
a.style.width = 200px;
}
else if(document.getElementById("hugeS").checked)
{
a.style.width = 300px;
}
}
The Javascript for the border changing function:
function changeCorners()
{
var bordertest;
bordertest = document.getElementById("buttontest");
if (document.getElementById("none").checked)
{
bordertest.style.borderRadius = 0px;
}
else if (document.getElementById("small").checked)
{
bordertest.style.borderRadius = 10px;
}
else if (document.getElementById("medium").checked)
{
bordertest.style.borderRadius = 20px;
}
else if (document.getElementById("large").checked)
{
bordertest.style.borderRadius = 30px;
}
else if (document.getElementById("total").checked)
{
bordertest.style.borderRadius = 40px;
}
}
The HTML for everything:
Button Text: <input type="text" onkeydown="changeText(event)" id="bText"><br />
Text Color: <input type="color" id="tColor" name="tColor" value="#3e3e3e" oninput="changeTextColor(tColor.value)"><br />
How Round: <input type="radio" name="roundness" id="none" checked="checked" onchange=changeCorners()>
<label for="none">Square</label>
<input type="radio" name="roundness" id="small" onchange=changeCorners()>
<label for="small">Small Roundness</label>
<input type="radio" name="roundness" id="medium" onchange=changeCorners()>
<label for="medium">Medium Roundness</label>
<input type="radio" name="roundness" id="large" onchange=changeCorners()>
<label for="large">Large Roundness</label>
<input type="radio" name="roundness" id="total" onchange=changeCorners()>
<label for="total">Completely Round</label><br />
Background Color: <input type="color" id="backColor" name="backColor" value="#dddddd" oninput="changeBgColor(backColor.value)"><br />
Shadow Color: <input type="color" id="shadColor" name="shadColor" value="#888888" oninput="changeShadColor(shadColor.value)"><br />
Button Size: <input type="radio" name="size" id="smallS" checked="checked" onchange=aBc()>
<label for="smallS">Small</label>
<input type="radio" name="size" id="mediumS" onchange=aBc()>
<label for="mediumS">Medium</label>
<input type="radio" name="size" id="largeS" onchange=aBc()>
<label for="largeS">Large</label>
<input type="radio" name="size" id="hugeS" onchange=aBc()>
<label for="hugeS">Extra Large</label><br />
<p><input type="button" value="" class="test1" id="buttontest"></p>
You need to quote your property values.
Things like a.style.width = 100px; should be a.style.width = "100px";

Categories