Javascript - Canvas - Create Circle on button click - javascript

iam trying to force my html button to draw a circle on canvas area but I dont know what Iam doing wrong. Can some1 point it for me?
JavaScript
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
// Funkcja
function drawCircle(size,xPos,Ypos,colour){ //draw circle
var xPos = Math.floor(Math.random() * 501);
var yPos = Math.floor(Math.random() * 501);
var size = Math.floor(Math.random() * 100);
var colour = '#' + Math.random().toString(16).substring(4); // random colour;
ctx.beginPath();
ctx.arc(xPos,yPos,size,0,2*Math.PI);
ctx.fillStyle = colour;
ctx.fill();
}
HTML
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<link rel="stylesheet" type="text/css" href="site.css">
<script type="text/javascript" src="site.js"></script>
</head>
<body>
<button style="margin:0;padding:0;position:relative;left:50px;top:50px;" onclick="drawCircle()">Draw Random Circle</button><br>
<div style = "width:500px; height:150px; margin:0 auto; padding:5px;">
<canvas id = "canvasArea" width = "500" height = "550" style = "border:2px solid black"></canvas>
</div>
</body> </html>

As Diego sais: wrong id.
Also, you better use HTML elements inside a function that's only triggered after the page is loaded.
Edit: Math.random produces a number between 0 and 1. So let's skip the "0."
so a substring from character 2, 6 characters long.
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<link rel="stylesheet" type="text/css" href="site.css">
<script type="text/javascript">
// global variables
var canvas;
var ctx;
// You do not have permission to read from ( nor write to ) HTML elements before the DOM is loaded.
window.onload = function() {
canvas = document.getElementById("canvasArea");
ctx = canvas.getContext("2d");
}
// Funkcja
function drawCircle(size, xPos, Ypos, colour) { //draw circle
var xPos = Math.floor(Math.random() * 501);
var yPos = Math.floor(Math.random() * 501);
var size = Math.floor(Math.random() * 100);
var colour = '#' + Math.random().toString(16).substr(2,6); // random colour;
// var colour = '#' + Math.random().toString(16).substring(4); // random colour;
ctx.beginPath();
ctx.arc(xPos, yPos, size, 0, 2 * Math.PI);
ctx.fillStyle = colour;
ctx.fill();
}
</script>
</head>
<body>
<button style="margin:0;padding:0;position:relative;left:50px;top:50px;" onclick="drawCircle()">Draw Random Circle</button><br>
<div style="width:500px; height:150px; margin:0 auto; padding:5px;">
<canvas id="canvasArea" width="500" height="550" style="border:2px solid black"></canvas>
</div>
</body>
</html>

You got the wrong ID in line:
var canvas = document.getElementById("myCanvas");
It must be:
var canvas = document.getElementById("canvasArea");
And thats it.
var canvas = document.getElementById("canvasArea");
var ctx = canvas.getContext("2d");
// Funkcja
function drawCircle(size,xPos,Ypos,colour){ //draw circle
var xPos = Math.floor(Math.random() * 501);
var yPos = Math.floor(Math.random() * 501);
var size = Math.floor(Math.random() * 100);
var colour = '#' + Math.random().toString(16).substring(4); // random colour;
ctx.beginPath();
ctx.arc(xPos,yPos,size,0,2*Math.PI);
ctx.fillStyle = colour;
ctx.fill();
}
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<link rel="stylesheet" type="text/css" href="site.css">
<script type="text/javascript" src="site.js"></script>
</head>
<body>
<button style="margin:0;padding:0;position:relative;left:50px;top:50px;" onclick="drawCircle()">Draw Random Circle</button><br>
<div style = "width:500px; height:150px; margin:0 auto; padding:5px;">
<canvas id = "canvasArea" width = "500" height = "550" style = "border:2px solid black"></canvas>
</div>
</body> </html>

Related

Flashing dots on canvas [duplicate]

This question already has answers here:
clearRect not working
(2 answers)
Closed 6 months ago.
I don't see why this code isn't working. It should just draw a white rectangle covering the screen. Then a randomly placed blue dot and wait for the loop to complete. And then repeat the cycle by drawing the white rectangle again and turning off the dot and then redrawing it.
<!DOCTYPE html>
<html lang="en-US">
<head>
<meta charset="UTF-8"/>
<title>Peripheral vision checker</title>
<script type="application/javascript">
function draw() {
// draw crosshairs
var onFor = 1000;
const intervalID = setInterval(mytimer, onFor);
function mytimer()
{
// draw white rects
function getRandomInt(max) {
return Math.floor(Math.random() * max);
}
var x = 1280;//will be equal to window height
var y = 720;//will be equal to window width
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
ctx.fillStyle = 'white';
var xcoor =getRandomInt(x);
var ycoor =getRandomInt(y);
ctx.fillRect(0, 0, x, y);
ctx.fillStyle = 'blue';
var radius = 10;
moveTo(xcoor,ycoor);
ctx.arc(xcoor, ycoor, radius, 0, 2 * Math.PI);
//console.log(xcoor + ' ' + ycoor);//just temporary, to see they work
ctx.fill();
}
}
</script>
</head>
<h1>Peripheral vision checker</h1>
<body onload="draw();">
<canvas id="canvas" width="1280" height="720"></canvas>
</body>
</html>
You need to beginPath then closePath
<!DOCTYPE html>
<html lang="en-US">
<head>
<meta charset="UTF-8" />
<title>Peripheral vision checker</title>
<script type="application/javascript">
function draw() {
// draw crosshairs
var onFor = 1000;
const intervalID = setInterval(mytimer, onFor);
function mytimer() {
// draw white rects
function getRandomInt(max) {
return Math.floor(Math.random() * max);
}
var x = 500; //will be equal to window height
var y = 250; //will be equal to window width
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
ctx.fillStyle = 'white';
var xcoor = getRandomInt(x);
var ycoor = getRandomInt(y);
ctx.fillRect(0, 0, x, y);
ctx.fillStyle = 'blue';
var radius = 10;
ctx.beginPath();
moveTo(xcoor, ycoor);
ctx.arc(xcoor, ycoor, radius, 0, 2 * Math.PI);
//console.log(xcoor + ' ' + ycoor);//just temporary, to see they work
ctx.fill();
// no need to:
// ctx.closePath();
}
}
</script>
</head>
<h1>Peripheral vision checker</h1>
<body onload="draw();">
<canvas id="canvas" width="500" height="250"></canvas>
</body>
</html>

Image reload into canvas

The goal of the code is as follows:
upload an image to a file
the user draws 4 points by clicking on the image
the x, y coordinates of the points are saved in an array
Now I have made a reset button in case the user is wrong to indicate the points.
The reset button should erase the array and reload the original image in the canvas.
I tried to invoke the function again but does not reload the image.
I'm new in javascript.
Anyone can help me?
Thanks in advance
<!DOCTYPE html>
<html lang="en">
<head>
<title>Title</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.0/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js"></script>
<style type="text/css">
#canvas {
border: 1px solid black;
}
</style>
</head>
<body>
<div class="container">
<h2>Title
<p id="demo"></p>
</h2>
<div class="card">
<div class="card-header">
<input type='file' id="fileUpload"/>
<button type="button" class="btn btn-secondary" id="resetButton" onclick="resetPoint()">Reset</button>
</div>
<div class="card-body">
<canvas id="canvas" width="500px" height="500px"></canvas>
</div>
<div class="card-footer">Footer</div>
</div>
<script>
var fileUpload = document.getElementById('fileUpload');
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext("2d");
function readImage() {
if ( this.files && this.files[0] ) {
var percorso = this.files[0]
var FR= new FileReader();
FR.onload = function(e) {
var img = new Image();
img.src = e.target.result;
img.onload = function() {
ctx.drawImage(img, 0, 0,500,500);
};
};
FR.readAsDataURL( this.files[0] );
}
}
fileUpload.onchange = readImage;
var coordinate=[];
canvas.onclick = function(e) {
if (coordinate.length < 4) {
var x = e.offsetX;
var y = e.offsetY;
ctx.beginPath();
ctx.fillStyle = 'blue';
ctx.arc(x, y, 3, 0, Math.PI * 2);
ctx.fill();
ctx.font="25px Arial";
ctx.fillText(coordinate.length+1,x+2, y+2);
var coordinataN=[x,y];
coordinate.push(coordinataN);
var coords = "X coords: " + x + ", Y coords: " + y;
document.getElementById("demo").innerHTML = coords;
}
};
function resetPoint() {
readImage()
coordinate.length = 0;
alert("Points deleted");
}
</script>
</body>
</html>
You need to clear the canvas first, then do your redrawing of the image.
You can clear the canvas by doing the following:
ctx.clearRect(0, 0, canvas.width, canvas.height);
You can add this line at the begining of your resetPoint() function.
Now that you want to keep the image, you need to save the uploaded image file somewhere so you can redraw it. I suggest making a variable outside your resetPoint() function:
var files;
and then at the beginning of your resetPoint() function add:
files = this.file
Aswell as change all the references to this.files to files.
See the snippet below for a working example:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Title</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.0/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js"></script>
<style type="text/css">
#canvas {
border: 1px solid black;
}
</style>
</head>
<body>
<div class="container">
<h2>Title
<p id="demo"></p>
</h2>
<div class="card">
<div class="card-header">
<input type='file' id="fileUpload"/>
<button type="button" class="btn btn-secondary" id="resetButton" onclick="resetPoint()">Reset</button>
</div>
<div class="card-body">
<canvas id="canvas" width="500px" height="500px"></canvas>
</div>
<div class="card-footer">Footer</div>
</div>
<script>
var fileUpload = document.getElementById('fileUpload');
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext("2d");
var files; // Add this
var img = new Image();
function readImage() {
files = this.files; // Set a reference to this.files (the image)
if (files && files[0] ) { // Update this line to only reference the files variable
var percorso = files[0]; // And this line
var FR= new FileReader();
FR.onload = function(e) {
img.src = e.target.result;
img.onload = function() {
ctx.drawImage(img, 0, 0,500,500);
};
};
FR.readAsDataURL( files[0] ); // And this line
}
}
fileUpload.onchange = readImage;
var coordinate=[];
canvas.onclick = function(e) {
if (coordinate.length < 4) {
var x = e.offsetX;
var y = e.offsetY;
ctx.beginPath();
ctx.fillStyle = 'blue';
ctx.arc(x, y, 3, 0, Math.PI * 2);
ctx.fill();
ctx.font="25px Arial";
ctx.fillText(coordinate.length+1,x+2, y+2);
var coordinataN=[x,y];
coordinate.push(coordinataN);
var coords = "X coords: " + x + ", Y coords: " + y;
document.getElementById("demo").innerHTML = coords;
}
};
function resetPoint() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
readImage()
coordinate.length = 0;
alert("Points deleted");
}
</script>
</body>
</html>

Why doesn't this code draw a square on the canvas?

I'm having trouble understanding why my code won't draw a square border on the canvas. I just started learning this stuff, and I'm afriad I'm missing something obvious...
<!DOCTYPE html>
<head>
<style type="text/css">
canvas {
background-image: url(uploads/1504975677.jpg);
width: 500px;
height: 334px;
}
</style>
<script type="text/javscript">
var x = 100;
var y = 100;
var width = 50;
var height = 50;
var canvas = document.getElementById('image');
var context = canvas.getContext('2d');
context.strokeStyle = 'white';
context.strokeRect(x, y, width, height);
</script>
<title>Test Website</title>
</head>
<body>
<canvas id="image"></canvas>
</body>
</html>
To clarify, I'm not trying to create a border for the canvas, I just want a box that is not filled in. All I get with this code is the background image and nothing drawn on top of it.
Below should be the format put your script before closing the body tag, Also change the color :-p
<!DOCTYPE html>
<head>
<style type="text/css">
canvas {
background-image: url(uploads/1504975677.jpg);
width: 500px;
height: 334px;
}
</style>
<title>Test Website</title>
</head>
<body>
<canvas id="image"></canvas>
<script type="text/javscript">
var x = 100; var y = 100; var width = 50; var height = 50; var canvas = document.getElementById('image'); var context = canvas.getContext('2d'); context.strokeStyle = 'black'; context.strokeRect(x, y, width, height);
</script>
</body>
</html>
var x = 100; var y = 100; var width = 50; var height = 50; var canvas = document.getElementById('image'); var context = canvas.getContext('2d'); context.strokeStyle = 'black'; context.strokeRect(x, y, width, height);
canvas {
width: 500px;
height: 334px;
}
<canvas id="image"></canvas>

How would I align circles horizontally using loops?

I have managed to get the circles on top of each other but I have no clue how to make a line of circles that do not overlap.
This is what I have gotten so far.
HTML
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
</head>
<body>
<canvas id="myCanvas" width="800" height="600"></canvas>
<script src="js/main.js"></script>
</body>
</html>
JavaScript
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext('2d');
for(var i = 0; i < 10; i++) {
ctx.fillStyle="rgba(0,0,0,0.5)";
fillCircle(200,200,i*20)
}
var width = window.innerWidth;
var height = 100;
function fillCircle(x, y, radius) {
ctx.beginPath();
ctx.arc(x, y, radius, 0, Math.PI * 2);
ctx.closePath();
ctx.fill();
}
The x-value of any next circle must be at least be the sum of the current and next circle radii beyond the current circle's x-value.
So if:
var currentCircleX=20
var currentCircleRadius=15
var nextCircleRadius=25
Then:
var nextCircleX = currentCircleX + currentCircleRadius + nextCircleRadius
But if you are also stroking the circles:
Since a context stroke will extend half-outside the defined path, you must also add half the lineWidth for each circle to avoid the circles touching:
// account for the lineWidth that extends beyond the arc's path
var nextCircleX =
currentCircleX + currentCircleRadius + nextCircleRadius + context.lineWidth
Example code and a Demo:
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var cw=canvas.width;
var ch=canvas.height;
ctx.fillStyle="rgba(0,0,0,0.5)";
var currentCircleX=0;
var currentCircleRadius=0;
for(var i = 0; i < 10; i++) {
var nextCircleRadius=i*20;
var nextCircleX=currentCircleX+currentCircleRadius+nextCircleRadius;
fillCircle(nextCircleX,200,nextCircleRadius);
currentCircleX=nextCircleX;
currentCircleRadius=nextCircleRadius;
}
function fillCircle(x, y, radius) {
ctx.beginPath();
ctx.arc(x, y, radius, 0, Math.PI * 2);
ctx.closePath();
ctx.fill();
}
body{ background-color: ivory; padding:10px; }
#canvas{border:1px solid red;}
<canvas id="canvas" width=300 height=300></canvas>

Making a portion of the canvas link to another webpage

I currently have a code that simply draws circles onto a canvas. However, I want those circles to be able to direct the user to a given link if he or she chooses to click on the circle again. I'm not entirely sure how to implement this though. Simply put, can drawn objects be used as a click event to direct user to another webpage?
http://jsfiddle.net/PTDy9/
<head>
<script src="https://code.jquery.com/jquery-1.11.1.min.js"></script>
</head>
<body>
<img id="graph" style=display:none src="http://i47.tinypic.com/29zr14o.jpg" alt="graph" >
<canvas id="myCanvas" width="700" height="400" style="border:1px solid #FFFFF;">
<script>
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
var img=document.getElementById("graph");
ctx.drawImage(img,0,0);
var color_list = ["#FFC0CB", "#00ffff", "#DA70D6", "#90EE90", "#FF8C00", "#CD853F"];
var color_iter = 0;
var bullet_y = 450;
var width = img.naturalWidth;
var height = img.naturalHeight;
jQuery(document).ready(function(){
$("#myCanvas").click(function(e){
var x = e.pageX - this.offsetLeft;
var y = e.pageY - this.offsetTop;
if (x < width && y < height) {
var ctx= this.getContext("2d");
ctx.beginPath();
ctx.arc(x, y, 10,0, 2*Math.PI);
color = color_list[color_iter];
ctx.strokeStyle = color;
ctx.fillStyle = color;
if (color_iter == color_list.length-1) {
color_iter = 0;
}
else {color_iter = color_iter + 1;}
ctx.fillStyle = color;
ctx.globalAlpha = .4;
ctx.fill();
ctx.stroke();
var a = document.createElement('a');
}
});
})
</script>
</body>
Here's one way let the user click on a circle to open a specified url in a new browser tab.
First create 1+ link objects specifying the click area on the canvas and the desired url:
var links=[];
addLink(75,75,30,"Google","http://www.google.com");
addLink(150,150,30,"CNN","http://www.cnn.com");
function addLink(x,y,radius,label,url){
links.push({
cx:x,
cy:y,
radius:radius,
label:label,
link:url
});
}
Then listen for mouse clicks and test if any link area was clicked.
If any specific link area was clicked, then open up the corresponding url in a new browser tab:
$("#canvas").mousedown(function(e){handleMouseDown(e);});
function handleMouseDown(e){
e.preventDefault();
e.stopPropagation();
mx=parseInt(e.clientX-offsetX);
my=parseInt(e.clientY-offsetY);
for(var i=0;i<links.length;i++){
var link=links[i];
var dx=link.cx-mx;
var dy=link.cy-my;
if(dx*dx+dy*dy<link.radius*link.radius){
window.open(link.link,'_blank');
}
}
}
Full Example Code:
<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" media="all" href="css/reset.css" /> <!-- reset css -->
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<style>
body{ background-color: ivory; }
#canvas{border:1px solid red;}
</style>
<script>
$(function(){
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 links=[];
addLink(75,75,30,"Google","http://www.google.com");
addLink(150,150,30,"CNN","http://www.cnn.com");
drawLinks();
$("#canvas").mousedown(function(e){handleMouseDown(e);});
function addLink(x,y,radius,label,url){
links.push({
cx:x,
cy:y,
radius:radius,
label:label,
link:url
});
}
function drawLinks(){
ctx.save();
ctx.fillStyle="green";
ctx.fillRect(0,0,canvas.width,canvas.height);
ctx.font="14px verdana";
ctx.textAlign="center";
ctx.textBaseline="middle";
for(var i=0;i<links.length;i++){
var link=links[i];
ctx.beginPath();
ctx.arc(link.cx,link.cy,link.radius,0,Math.PI*2);
ctx.closePath();
ctx.fillStyle="blue";
ctx.fill();
ctx.fillStyle="white";
ctx.fillText(link.label,link.cx,link.cy);
}
ctx.restore();
}
function handleMouseDown(e){
e.preventDefault();
e.stopPropagation();
mx=parseInt(e.clientX-offsetX);
my=parseInt(e.clientY-offsetY);
for(var i=0;i<links.length;i++){
var link=links[i];
var dx=link.cx-mx;
var dy=link.cy-my;
if(dx*dx+dy*dy<link.radius*link.radius){
window.open(link.link,'_blank');
}
}
}
}); // end $(function(){});
</script>
</head>
<body>
<canvas id="canvas" width=300 height=300></canvas>
</body>
</html>

Categories

Resources