Show HTML Slider variable derived through javascript on HTML Page - javascript

I have a slider that changes the width of circles on a bullseye on a canvas. I want to display that bandwidth beneath the canvas. Like just a simple Current bandwidth: x
I am having trouble figuring out how to do this.
I've tried using span and documentwrite(), but part of the problem is I can't really figure out how to get the variable in the first place.
<!DOCTYPE html>
<html>
<head>
<script src="bullseye.js"></script>
<title>Bull's Eye</title>
</head>
<body>
<canvas id="testCanvas" style="border: 1px solid;" width="400" height="400"> </canvas>
<p></p>
<div style="position:absolute; top:420px; left:10px">
<label for="radius">Bandwidth</label>
<input type="range" id="width" min="5" max="50" step="5" value="25" oninput="sliderModule.drawPattern()"></input>
<p>Current Bandwidth: <span id="show"></span></p>
</div>
</body>
</html>
here is the javascript
var sliderModule = (function(win, doc) {
win.onload = init;
// canvas and context variables
var canvas;
var context;
// center of the pattern
var centerX, centerY;
function init() {
canvas = doc.getElementById("testCanvas");
context = canvas.getContext("2d");
centerX = canvas.width / 2;
centerY = canvas.height / 2;
drawPattern();
}
function drawPattern() {
var width = doc.getElementById("width").value;
var radius = 200;
var colorTog = 1;
context.clearRect(0, 0, canvas.width, canvas.height);
while (radius > 0) {
context.beginPath();
context.arc(centerX, centerY, radius, 0, 2 * Math.PI);
if (colorTog == 1){
context.fillStyle = 'red';
} else {
context.fillStyle = 'blue';
}
context.fill();
context.closePath();
radius = radius - width;
if (colorTog == 1){
colorTog = 0;
} else {
colorTog = 1;
}
}
}
return {
drawPattern: drawPattern
};
})(window, document);

Related

Change Ball's color after bounce and make the ball an image

So I wanted to make the DVD bouncing screen in HTML and Javascript, but I am having trouble getting the ball to be the DVD logo and changing the color when a bounce happens ball or image. Does anyone know how to change the ball to be an image and change its color when a bounce happens?
<html>
<head>
</head>
<body>
<script>
var context;
var x=100;
var y=100;
var dx=5;
var dy=2;
function init()
{
context= myCanvas.getContext('2d');
setInterval(draw,20);
}
function draw()
{
//base_image = new Image();
//base_image.src = 'dvd.png';
//context.drawImage(base_image, 100, 100);
//base_image.arc(x,y,20,0,Math.PI*2,true);
context.clearRect(0,0, 600,600);
context.beginPath();
context.fillStyle="#0000ff";
//Draws a circle of radius 20 at the coordinates 100,100 on the canvas
context.arc(x,y,20,0,Math.PI*2,true);
context.closePath();
context.fill();
// Boundary Logic
if (x < 0 || x > 600){
dx = -dx;
context.fillStyle="#77ff00";
}
if (y < 0 || y > 600){
dy = -dy;
}
x+=dx;
y+=dy;
}
</script>
//<img src="dvd.png" id="dvd" width="100" height="100">
<body onLoad="init();">
<canvas id="myCanvas" width="600" height="600" >
</canvas>
</body>
</html>
Here you go. I edited your code a bit.
<html>
<head>
</head>
<body onLoad="init();">
<script>
var context;
var x=100;
var y=100;
var dx=5;
var dy=2;
var image;
var image_height = 100;
var image_width = 100;
var myCanvas;
function init()
{
myCanvas = document.getElementById("myCanvas");
context= myCanvas.getContext('2d');
image = new Image();
image.onload = function() {
context.drawImage(image, x,y, image_width, image_height);
}
image.src="https://img.icons8.com/ios/452/dvd-logo.png";
setInterval(draw,20);
}
function draw()
{
context.clearRect(0,0, 600,600);
context.drawImage(image, x,y, 100, 100);
context.globalCompositeOperation = "source-in";
// draw color
var right_bound = 600 - image_width;
var bottom_bound = 600 - image_height;
// Boundary Logic
if (x < 0 || x > right_bound){
dx = -dx;
context.fillStyle = "#09f";
}
if (y < 0 || y > bottom_bound){
dy = -dy;
context.fillStyle = "#ff0";
}
context.fillRect(0, 0, 600, 600);
//reset back to default global composite
context.globalCompositeOperation = "source-over";
x+=dx;
y+=dy;
}
</script>
<canvas id="myCanvas" width="600" height="600"> </canvas>
</body>
</html>

JS Canvas: How to make rectangle go back and forth once it reaches the boundary

So I have this rectangle that animates across to the right. How can I get the rectangle to reverse it when it hits the boundaries. I'm trying to make it go back and forth.
<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'>
window.onload=function(){
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
var x = 0;
var y = 50;
var width = 10;
var height = 10;
function animate() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.fillRect(x, y, width, height);
x++;
if(x <= 490) {
setTimeout(animate, 33);
}
}
animate();
}
</script>
</head>
<body>
<canvas id="canvas" width="500" height="400"
style="border: 1px solid #000000;"></canvas>
</body>
</html>
https://codepen.io/forTheLoveOfCode/pen/wqdpeg
Is that what you need? (link to codepen above).
var canvas = document.getElementById("canvas_id");
var context = canvas.getContext('2d');
var x=5;
var y=5;
var velocity = 10;
function move(){
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
x =x + velocity
if ((x+50)>canvas.width || x<0){
velocity *=-1;
}
draw()
}
function draw(){
context.fillStyle = "#E80C7A";
context.strokeStyle = "#000000";
context.lineWidth = '3';
context.fillRect(x, y, 50, 100);
context.strokeRect(x, y, 50, 100);
}
setInterval(move, 100);
<html>
<body>
<canvas id = "canvas_id">
</canvas>
</body>
</html>
here's a solution with boundaries detection
window.onload=function(){
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
var x = 0;
var y = 50;
var width = 10;
var height = 10;
var speed = 10; // speed
function animate() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.fillRect(x, y, width, height);
if(
(x >= 500 - width && speed > 0) || // going to the right and bound reached
(x <= 0 && speed < 0) // going to the left and bound reached
) {
speed *= -1; // inverting the direction
}
x += speed;
setTimeout(animate, 33);
}
animate();
}
<canvas id="canvas" width="500" height="400"
style="border: 1px solid #000000;"></canvas>
consider using requestAnimationFrame instead of setTimeout to do this kind of work.

How to zoom to center of canvas, not to center of context

I have a canvas, size 400 x 400. On it, i have drawn a map area, 200 x 200.
I have translated this to the center of the canvas. I can zoom in and out, all is well. But, when i pan, it zooms from the center of my map area. I want it to always zoom from the center of the canvas no matter where the map area is. I think i need to negate the pan coords somehow, but i can't figure it out.
Here is my code:
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
var canvas1 = document.getElementById("canvasX");
var ctxX = canvas1.getContext("2d");
var cw = canvas.width;
var ch = canvas.height;
var mapW = 200;
var mapH = 200;
var panX=0;
var panY=0;
var scaleFactor=1.00;
drawTranslated();
function zoomIn(){
document.getElementById("zoomin").click();
{ scaleFactor*=1.1; drawTranslated(); };
}
function zoomOut(){
document.getElementById("zoomout").click();
{ scaleFactor/=1.1; drawTranslated(); };
}
function panUp(){
document.getElementById("panup").click();
{ panY-=25; drawTranslated(); };
}
function panDown(){
document.getElementById("pandown").click();
{ panY+=25; drawTranslated(); };
}
function panLeft(){
document.getElementById("panleft").click();
{ panX-=25; drawTranslated(); };
}
function panRight(){
document.getElementById("panright").click();
{ panX+=25; drawTranslated(); };
}
function drawTranslated(){
// canvas
ctx.clearRect(0,0,cw,ch);
ctx.save();
ctx.translate(cw/2, ch/2);
ctx.translate(panX,panY);
ctx.scale(scaleFactor, scaleFactor);
ctx.fillStyle = "Green";
ctx.fillRect(mapW/-2, mapH/-2, mapW, mapH);
ctx.restore();
// canvasX
ctxX.clearRect(0,0,cw,ch);
ctxX.save();
ctxX.translate(cw/2, ch/2);
ctxX.beginPath();
ctxX.moveTo(0, 25);
ctxX.lineTo(0, -25);
ctxX.moveTo(-25, 0);
ctxX.lineTo(25, 0);
ctxX.closePath();
ctxX.lineWidth = 1;
ctxX.strokeStyle = 'Black';
ctxX.stroke();
ctxX.restore();
}
#wrapper {position: relative;}
canvas {position: absolute; border: 1px solid Black;}
<!DOCTYPE html>
<html>
<body>
<div id="wrapper">
<button id="zoomin" class="nav" title="Zoom In" onclick="zoomIn()">+</button>
<button id="zoomout" class="nav" title="Zoom Out" onclick="zoomOut()">−</button>
<button id="panup" class="nav" title="Up" onclick="panUp()">⇧</button>
<button id="pandown" class="nav" title="Down" onclick="panDown()">⇩</button>
<button id="panleft" class="nav" title="Left" onclick="panLeft()">⇦</button>
<button id="panright" class="nav" title="Right" onclick="panRight()">⇨</button>
</div>
<div id="wrapper">
<canvas id="myCanvas" width="400" height="400"></canvas>
<canvas id="canvasX" width="400" height="400"></canvas>
</div>
</body>
</html>
After some time of trying to find some equation to solve this, i think i have found the solution.
ctx.translate(panX,panY);
ctx.scale(scaleFactor, scaleFactor);
By panning first, then scaling, it will zoom from the center of the context (In this case the green square). However, simply changing it around to:
ctx.scale(scaleFactor, scaleFactor);
ctx.translate(panX,panY);
it will zoom from the center of the canvas.
It seems to do what i want it to, so unless i am mistaken, i believe this is the answer.
I have included another snippet. The only changes are those 2 lines, but i think it would be helpful for people to able to see the difference it makes.
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var canvas1 = document.getElementById("canvasX");
var ctxX = canvas1.getContext("2d");
var cw = canvas.width;
var ch = canvas.height;
var mapW = 200;
var mapH = 200;
var panX = 0;
var panY = 0;
var scaleFactor = 1.00;
drawTranslated();
function zoomIn() {
document.getElementById("zoomin").click(); {
scaleFactor *= 1.1;
drawTranslated();
};
};
function zoomOut() {
document.getElementById("zoomout").click(); {
scaleFactor /= 1.1;
drawTranslated();
};
};
function panUp() {
document.getElementById("panup").click(); {
panY -= 25;
drawTranslated();
};
};
function panDown() {
document.getElementById("pandown").click(); {
panY += 25;
drawTranslated();
};
};
function panLeft() {
document.getElementById("panleft").click(); {
panX -= 25;
drawTranslated();
};
};
function panRight() {
document.getElementById("panright").click(); {
panX += 25;
drawTranslated();
};
};
function drawTranslated() {
// canvas
ctx.clearRect(0, 0, cw, ch);
ctx.save();
ctx.translate(cw / 2, ch / 2);
ctx.scale(scaleFactor, scaleFactor);
ctx.translate(panX, panY);
ctx.fillStyle = "Green";
ctx.fillRect(mapW / -2, mapH / -2, mapW, mapH);
ctx.restore();
// canvasX
ctxX.clearRect(0, 0, cw, ch);
ctxX.save();
ctxX.translate(cw / 2, ch / 2);
ctxX.beginPath();
ctxX.moveTo(0, 25);
ctxX.lineTo(0, -25);
ctxX.moveTo(-25, 0);
ctxX.lineTo(25, 0);
ctxX.closePath();
ctxX.lineWidth = 1;
ctxX.strokeStyle = 'Black';
ctxX.stroke();
ctxX.restore();
};
#wrapper {
position: relative;
}
canvas {
position: absolute;
border: 1px solid Black;
}
<div id="wrapper">
<button id="zoomin" class="nav" title="Zoom In" onclick="zoomIn()">+</button>
<button id="zoomout" class="nav" title="Zoom Out" onclick="zoomOut()">−</button>
<button id="panup" class="nav" title="Up" onclick="panUp()">⇧</button>
<button id="pandown" class="nav" title="Down" onclick="panDown()">⇩</button>
<button id="panleft" class="nav" title="Left" onclick="panLeft()">⇦</button>
<button id="panright" class="nav" title="Right" onclick="panRight()">⇨</button>
</div>
<div id="wrapper">
<canvas id="canvas" width="400" height="400"></canvas>
<canvas id="canvasX" width="400" height="400"></canvas>
</div>
There surely is a better way but in Fabric.js you can do
canvas.zoomToPoint(new fabric.Point(canvas.width / 2, canvas.height / 2), canvas.getZoom() / ZOOM_PERCENT);
See more here Canvas
For a more pure solution, you can also try translating the context by half the canvas size using
ctx.translate()
A fiddle that might help
http://jsfiddle.net/m1erickson/QEuw4/

Drawing on canvas does not happen in javascript

I'm trying to make a canvas of squers and rectangles that appear randomly, the amount of them is the users choice. after they input the numbers of eace of them, press a button-it should appear on the canvas. in my code it does not happen, and i cant understand why! making me crazy here. I'm obviously missing something here, and i guess its a very stupid thing.
function draw() {
var drawing = document.getElementById("canvas");
var context = drawing.getContext("2d");
saveImage();
}
//save the user input to use it later
var numOfRect = parseInt(document.getElementById("inSquer").value);
var numOfCirc = parseInt(document.getElementById("inCircle").value);
//This function will draw on the canvas
function paint(numOfRect, numOfCirc) {
for (var makeIt = 0; makeIt < numOfRect; makeIt++) {
makeRect(drawing, context);
makeCircle(drawing, context);
}
}
//This function draw the circles
function makeCircle(drawing, context) {
var radius = Math.floor(Math.random() * 80);
var x = Math.floor(Math.random() * canvas.width);
var y = Math.floor(Math.random() * canvas.height);
context.beginPath();
context.arc(x, y, radius, 0, 2 * Math.PI);
context.fillStyle = "blue";
context.fill();
}
//This function draw the squers
function makeRect(drawing, context) {
var w = Math.floor(Math.random() * 50);
var x = Math.floor(Math.random() * canvas.width);
var y = Math.floor(Math.random() * canvas.height);
context.fillStyle = "yellow";
context.fillRect(x, y, w, w);
}
//function to save the canvas as an image
function saveImage() {
var canvas = document.getElementById("canvas");
canvas.onclick = function() {
window.location = canvas.toDataURL("image/png");
};
}
#canvas {
margin-left: 150px;
border: 1px solid black;
}
<html>
<head>
<script src="js.js">
</script>
<link href="design.css" rel="stylesheet" />
</head>
<body onload="draw()">
<canvas id="canvas" width="1200" height="750"></canvas>
</br>
</br>
<span>
How many Circles do you want?
<input id="inCircle"></input>
</span>
</br>
How many Squers do you want?
<input id="inSquer"></input>
</br>
<button id="creat" onclick="paint()">Creat My Work</button>
</body>
</html>
paint(numOfRect, numOfCirc) wants 2 parameters, but <button id="creat" onclick="paint()">Creat My Work</button> is not giving any.
Also
var numOfRect = parseInt(document.getElementById("inSquer").value);
var numOfCirc = parseInt(document.getElementById("inCircle").value);
does not exactly do anything, as the values are empty when that code runs.
Try changing the paint function like so:
function paint()
{
var numOfRect = parseInt(document.getElementById("inSquer").value);
var numOfCirc = parseInt(document.getElementById("inCircle").value);
for (var makeIt = 0; makeIt < numOfRect; makeIt++)
{
makeRect(drawing, context);
makeCircle(drawing, context);
}
}
Please consider the following snippet.
First of all, your paint() function was missing two arguments. Apart from that, I would recommend to define all the variables on top of your script, so it's easier to keep track.
I have added a few comments in the code to highlight the changes.
Also I have removed a few redundant DOM interactions.
// Wait for DOM to be loaded.
document.addEventListener("DOMContentLoaded", function(event) {
// Keep references to elements, so we could interact with them later.
var drawing = document.getElementById("canvas");
var context = drawing.getContext("2d");
var inSquer = document.getElementById("inSquer");
var inCircle = document.getElementById("inCircle");
var button = document.getElementById("creat");
// Attach event listeners to the button and canvas element.
button.addEventListener("click", function() {
// Retrieve values from input fields every time you click.
paint(parseInt(inSquer.value), parseInt(inCircle.value));
});
drawing.addEventListener("click", function() {
saveImage();
});
// Function to save the canvas as an image.
function saveImage() {
window.location = drawing.toDataURL("image/png");
}
// This function will draw on the canvas.
function paint(numOfRect, numOfCirc) {
for (var makeIt = 0; makeIt < numOfRect; makeIt++) {
makeRect(drawing, context);
makeCircle(drawing, context);
}
}
// This function draw the circles.
function makeCircle(drawing, context) {
var radius = Math.floor(Math.random() * 80);
var x = Math.floor(Math.random() * canvas.width);
var y = Math.floor(Math.random() * canvas.height);
context.beginPath();
context.arc(x, y, radius, 0, 2 * Math.PI);
context.fillStyle = "blue";
context.fill();
}
// This function draw the squers.
function makeRect(drawing, context) {
var w = Math.floor(Math.random() * 50);
var x = Math.floor(Math.random() * canvas.width);
var y = Math.floor(Math.random() * canvas.height);
context.fillStyle = "yellow";
context.fillRect(x, y, w, w);
}
});
#canvas {
margin-left: 150px;
border: 1px solid black;
}
<html>
<head>
</head>
<body>
<canvas id="canvas" width="1200" height="750"></canvas>
<br/>
<br/>
<span>
How many Circles do you want?
<input id="inCircle" />
</span>
<br/>How many Squers do you want?
<input id="inSquer" />
<br/>
<button id="creat">Creat My Work</button>
</body>
</html>

Moving text inside canvas using html5

I am new to html5 development could anyone tell me how to make text to move one side to other horizontally inside canvas..
Here's an example of how to animate text back and forth across the screen:
<html>
<head>
<title>HTML 5 Animated Text</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript">
var context;
var text = "";
var textDirection ="";
$(function()
{
context = document.getElementById("cvs").getContext("2d");
setInterval("animate()", 30);
textDirection ="right";
textXpos = 5;
text = "Animation!";
});
function animate() {
// Clear screen
context.clearRect(0, 0, 500, 500);
context.globalAlpha = 1;
context.fillStyle = '#fff';
context.fillRect(0, 0, 500, 500);
var metrics = context.measureText(text);
var textWidth = metrics.width;
if (textDirection == "right") {
textXpos += 10;
if (textXpos > 500 - textWidth) {
textDirection = "left";
}
}
else {
textXpos -= 10;
if (textXpos < 10) {
textDirection = "right";
}
}
context.font = '20px _sans';
context.fillStyle = '#FF0000';
context.textBaseline = 'top';
context.fillText ( text, textXpos, 180);
}
</script>
</head>
<body>
<div id="page">
<canvas id="cvs" width="500" height="500">
Your browser does not support the HTML 5 Canvas.
</canvas>
</div>
</body>
</html>
In action: http://jsfiddle.net/bS79G/
You can also use the canvas store(), translate() and restore() methods to animate the text.
suppose if you want to move the text from right side to left side, then you can use the following code snippet:
Refer site: http://www.authorcode.com/text-animation-in-html5/
var can, ctx, step, steps = 0,
delay = 20;
function init() {
can = document.getElementById("MyCanvas1");
ctx = can.getContext("2d");
ctx.fillStyle = "blue";
ctx.font = "20pt Verdana";
ctx.textAlign = "center";
ctx.textBaseline = "middle";
step = 0;
steps = can.height + 50;
RunTextRightToLeft();
}
function RunTextRightToLeft() {
step++;
ctx.clearRect(0, 0, can.width, can.height);
ctx.save();
ctx.translate(can.width / 2, step);
ctx.fillText("Welcome", 0, 0);
ctx.restore();
if (step == steps)
step = 0;
if (step < steps)
var t = setTimeout('RunTextRightToLeft()', delay);
}

Categories