HTML5 canvas with dynamic user input - html

I will start off by admitting I have never used canvas before so I don't know if this is possible but I can't seem to find the solution.
I am trying to create a canvas that draws a simple regular polygon shape (all sides are equal) in canvas based on the number of sides and size of the polygon that the user inputs most likely in HTML/PHP form. Nothing is actually saved to a server or database, just used for the one drawing.
Does anyone have any advice?

You should use a JavaScript library to make it easier to draw on the canvas.
Here's a really good demo of the functionality that you're looking for:
http://fabricjs.com/
And the the library is Fabric.js, which you can download here: http://fabricjs.com/

I looked up on google and there was an interesting tutorial/code which draws a regular polygon with n-sides & size. So I thought of making a function out of it, one of the technical problems I encountered is that when the canvas is drawed and I click to draw another canvas, the second canvas is "overwritten" on the first one. Luckily someone here solved this problem by clearing the canvas.
So here's my code, you may change it to your needs:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Regular Polygon</title>
</head>
<body>
<canvas id="regular_polygon" width="400" height="400"></canvas>
<p>Polygon drawer:</p>
<p>Number of sides <input type="text" id="nSides"></p>
<p>Size <input type="text" id="size"></p>
<p>Color <input type="text" id="color"></p>
<p>Width <input type="text" id="width"></p>
<button id="draw">Draw!</button>
<script type="text/javascript">
function polygon (element_id, nSides, psize, pcolor, pwidth) {
var c = document.getElementById(element_id);
c.width = c.width;
var cxt = c.getContext("2d");
var numberOfSides = nSides,
size = psize,
Xcenter = c.width/2,
Ycenter = c.height/2;
cxt.beginPath();
cxt.moveTo (Xcenter + size * Math.cos(0), Ycenter + size * Math.sin(0));
for (var i = 1; i <= numberOfSides;i += 1) {
cxt.lineTo (
Xcenter + size * Math.cos(i * 2 * Math.PI / numberOfSides),
Ycenter + size * Math.sin(i * 2 * Math.PI / numberOfSides)
);
}
cxt.strokeStyle = pcolor;
cxt.lineWidth = pwidth;
cxt.stroke();
}
(function () {
polygon("regular_polygon", 3, 40, "#000000", 2);
document.querySelector('#draw').addEventListener('click', function (e) {
e.preventDefault();
var nSides = document.querySelector('#nSides'),
size = document.querySelector('#size'),
color = document.querySelector('#color'),
width = document.querySelector('#width');
polygon("regular_polygon", nSides.value, size.value, color.value, width.value);
});
})();
</script>
</body>
</html>

Related

A hover-activated 3D Parallax effect on my website

I want to create a hover-activated 3D Parallax Effect for my homepage.
I want to achive something like that:
https://www.hellomonday.com/
It has a 3D effect but also it is responsive to my mouse movement. What should I search? How can I create this effect?
Parallax.js by Matt Wagerfield (#mwagerfield) and Claudio Guglieri (#claudioguglieri)
It is a robust little parallax engine, giving you a quick, simple api to get going with all your parallax needs. Forget scrolling though, parallax.js utilizes your devices orientation and will fall back to cursor positions if no motion detection is available… this really gives you that sexy responsive feel.
May be this could help you to acheive what you are seeking for :)
Alternatively if you want to use Primitive JS Then you have to track the movement of mouse and trigger some event accordingly.
<!DOCTYPE html>
<html>
<head>
<style>
div {
width: 200px;
height: 100px;
border: 1px solid black;
}
</style>
</head>
<body>
<div id="myDIV"></div>
<p>Mouse over the rectangle above, and get the coordinates of your mouse pointer.</p>
<p id="demo"></p>
<p id="demo1"></p>
<script>
document.getElementById("myDIV").addEventListener("mousemove", function(event) {
myFunction(event);
});
function myFunction(e) {
var x = e.clientX;
var y = e.clientY;
var coor = "Coordinates: (" + x + "," + y + ")";
document.getElementById("demo").innerHTML = coor;
if( x == "54")
alert("Cordinate triggered")
}
</script>
As soon as you hit x coordinate as 54, alert box will appear

Random Image Position in programming website?

I want to make it so I have "enemies" spawn in the background (not THE background, just images on top of it) of a particular webpage at random heights and scroll across the screen. Right now I have something like:
<script>
function numberRandomizer(){
var x = Math.floor((Math.random() * 500) + 300); //random number between 300 and 800
return x;
}
</script>
I've tried 2 methods to applying this random variable X to the images that loop by scrolling on screen:
1) Doing what I thought would work and editing each image to get a random value for top and left
<marquee behavior="scroll" direction="left" scrollamount="numberRandomizer()"><img src="/aboutme/enemy.png" width="120" height="80" top="numberRandomizer()" left="numberRandomizer()"/><p></marquee>
2) Even though as far as I know it would make all enemies have the same position, try out CSS styling to make the placement random just to see if it would work:
<style>
img {
top: numberRandomizer();
left: numberRandomizer();
}
</style>
Neither style works in setting a random value for the image location, am I getting a minor thing wrong or going about this completely the wrong way?
As a bonus question: Is it possible to set marquee to go a random direction per image?
You can make the same thing using plain javascript too
html:
<marquee behavior="scroll" direction="left" id="elem">Test</marquee>
<br/>
<button id="butR">Right</button>
<button id="butL">Left</button>
<div class="area">
<div id="enemy"></div>
</div>
Js:
document.getElementById('butR').addEventListener("click", function(){
document.getElementById('elem').setAttribute("direction", "right");
});
document.getElementById('butL').addEventListener("click", function(){
document.getElementById('elem').setAttribute("direction", "left");
});
function numberRandomizer(){
var x = Math.floor((Math.random() * 250) + 50); //random number between 50 and 300
return x;
}
document.getElementById('enemy').style.top = numberRandomizer() + 'px';
document.getElementById('enemy').style.left = numberRandomizer() + 'px';
I've added also a way to change marque direction. Take a look at this fiddle:
https://jsfiddle.net/oyv324z9/
As a couple people said, you can't mix JS and CSS. If you are using jQuery though, this is pretty simple. Basically, you want to use jQuery to add CSS styles to the img. Something like this.
//your trigger here and then..
$( "#your_img_id" ).css( "left", function(index) {
return index * numberRandomizer() ;
});
$( "#your_img_id" ).css( "right", function(index) {
return index * numberRandomizer() ;
});

How to hide header elements if core-scroll-header-panel is condensed?

My page is looking very similar to: https://www.polymer-project.org/components/core-scroll-header-panel/demo.html. The only difference is that my page has the keepCondensedHeader flag set.
What I want to do now (if at all possible):
Hide the title (or any one of the elements shown in the condensed header) if the header is condensed.
Any pointers would be greatly appreciated.
Actually the javascript inside the demo file gives a very good hint of how something like this can be done easily.
I copied the whole html and js here with two more lines that hide the title when the header is condensed.
The reason that why I put 128 m as the translate Y is because the max header height is 192 d.height and the condensed height is 64 d.condensedHeight. When the header is condensed, it travels in y axis for a distance of 128 m (192 - 64 d.height - d.condensedHeight).
<body unresolved>
<core-scroll-header-panel condenses keepcondensedheader>
<core-toolbar class="tall">
<core-icon-button icon="arrow-back"></core-icon-button>
<div flex></div>
<core-icon-button icon="search"></core-icon-button>
<core-icon-button icon="more-vert"></core-icon-button>
<div class="bottom indent title">Title</div>
</core-toolbar>
<div class="content">
<sample-content size="100"></sample-content>
</div>
</core-scroll-header-panel>
<script>
// custom transformation: scale header's title
var titleStyle = document.querySelector('.title').style;
// added code - here we need to obtain the title div as well
var title = document.querySelector('.title');
addEventListener('core-header-transform', function (e) {
var d = e.detail;
var m = d.height - d.condensedHeight;
var scale = Math.max(0.75, (m - d.y) / (m / 0.25) + 0.75);
titleStyle.transform = titleStyle.webkitTransform =
'scale(' + scale + ') translateZ(0)';
// added code - here we hide the title when the header is condensed
title.hidden = d.y == m;
});
</script>
</body>
Hope this helps!
Update
Actually now that I think about, it's probably a better idea to animate the opacity of the title rather than show/hide it. It would give much better user experience along with core-scroll-header-panel's smooth scrolling and fading background!
Thanks to core-animation it's quite straight forward.
First we need to include this reference.
<link rel="import" href="../core-animation/core-animation.html">
Then the definition of the fade in & out animations.
<body unresolved>
<!--define the opacity animations-->
<core-animation id="out" fill="forwards" duration="400">
<core-animation-keyframe>
<core-animation-prop name="opacity" value="1"></core-animation-prop>
</core-animation-keyframe>
<core-animation-keyframe>
<core-animation-prop name="opacity" value="0"></core-animation-prop>
</core-animation-keyframe>
</core-animation>
<core-animation id="in" fill="forwards" duration="400">
<core-animation-keyframe>
<core-animation-prop name="opacity" value="0"></core-animation-prop>
</core-animation-keyframe>
<core-animation-keyframe>
<core-animation-prop name="opacity" value="1"></core-animation-prop>
</core-animation-keyframe>
</core-animation>
Lastly, we call them inside the core-header-transform handler.
// animation variables
var fadeIn, fadeOut;
// create a local bool to ensure the 'fade in' animation is only called once
var condensed = false;
// retrieve the animations and set their targets
addEventListener('polymer-ready', function (e) {
fadeOut = document.getElementById('out');
fadeOut.target = title;
fadeIn = document.getElementById('in');
fadeIn.target = title;
});
addEventListener('core-header-transform', function (e) {
var d = e.detail;
var m = d.height - d.condensedHeight;
var scale = Math.max(0.75, (m - d.y) / (m / 0.25) + 0.75);
titleStyle.transform = titleStyle.webkitTransform =
'scale(' + scale + ') translateZ(0)';
// when the header is condensed, we fade it out
if (d.y == m) {
condensed = true;
fadeOut.play();
}
// otherwise, we fade it back in
else {
if (condensed) {
condensed = false;
fadeIn.play();
}
}
});

HTML5 progress bar animation

I am using an HTML5 progress bar in my app. I would like to know if there is any way to control the animation speed of the progress bar. I want to show the progress after a certain interval, which I did using the setTimeout method of javascript so that it sets the value after the screen has been rendered. But the animation is too fast. Is there any way to control it?
Thanks.
I'm not sure I understand what you mean by "animation" but here is an example of using the progress bar while controlling the speed of progression: http://jsfiddle.net/526hM/
Html:
<progress max="200" value="1"></progress>
<div id="val"></div>
Script:
$(document).ready(function(){
var interval = 2, //How much to increase the progressbar per frame
updatesPerSecond = 1000/60, //Set the nr of updates per second (fps)
progress = $('progress'),
animator = function(){
progress.val(progress.val()+interval);
$('#val').text(progress.val());
if ( progress.val()+interval < progress.attr('max')){
setTimeout(animator, updatesPerSecond);
} else {
$('#val').text('Done');
progress.val(progress.attr('max'));
}
}
setTimeout(animator, updatesPerSecond);
});
Here is example.
JavaScript function:
window.onload = addTenPercent();
function addTenPercent() {
var bar = document.getElementById("progressBar");
setInterval(addTenPercent, 100);
bar.value += 5;
};
HTML:
<progress id="progressBar" max="100" value="0"></progress>
Mantas' answer above looks good and works (without having to use jQuery), but I wonder if we could also use the setTimeout function? Would setTimeout in a recursive function that exits after 100 iterations also work? Copying Mantas' code from above and changing it a little:
JavaScript:
function onWindowLoad(){ // to be called by onload event
var bar = document.getElementById("progressBar");
addOne();
}
function addOne() {
if (bar.value < 100) { // this is the max value of the bar and the # of iterations
setTimeout(addOne, 80); // this literal value controls the speed
bar.value += 1;
}else{
return;
}
}
HTML:
<progress id="progressBar" max="100" value="0"></progress>

How can I make concentric circles in HTML respond to mouseOver properly?

On my web page, I'd like to have a group of several concentric circles of varying size, with each displaying a menu when they are moused over.
So far, I have created 4 pictures that is 100% transparent except for the circle and have layered them on top of each other. However, when I mouse-over the group of circles, the transparent part of the top image causes the mouse-over event to fire. How can I deal with this?
For reference, here is the code that I have so far.
<html>
<head>
<style type="text/css">
img
{
position:fixed;
left: 0;
bottom: 0;
}
</style>
<title>Circle Test</title>
</head>
<body>
<img src="Circle2.png" onMouseover="alert('Button2')"/>
<img src="Circle4.png" onMouseover="alert('Button4')"/>
<img src="Circle3.png" onMouseover="alert('Button3')"/>
<img src="Circle1.png" onMouseover="alert('Button1')"/>
</body>
</html>
This would be hard with pure images as it's difficult to tell when the mouse is actually over the circle part of the image. I would suggest a client side image map as they let you define clickable areas in non-rectangular shapes. Set the href to something like "javascript:circleClicked(); void 0;" :D
There's no way to tell that the mouse is over a transparent pixel of your circle: you must check if the mouse intersects with the actual circle (yeah, really). Actually, that's easier than it might seem. Considering your circle's diameter is your image's width (which appears quite possible to me), you just have to check that the mouse cursor is within the radius of the circle (which would be width / 2):
function intersectsCircle(diameter, center, mousePosition)
{
var radius = diameter / 2;
// compute the distance between mousePosition and center
var deltaX = mousePosition.x - center.x;
var deltaY = mousePosition.y - center.y;
return Math.sqrt(deltaX * deltaX + deltaY * deltaY) < radius;
}
And the you just have to pass the required informations (my Javascript's rusty so what follows might not be exactly accurate, especially double-check the events part):
function intersects(target, event)
{
var center = {x: target.x + target.width / 2, y: target.y + target.height / 2};
var mousePosition = {x: event.clientX, y: event.clientY};
if(intersectsCircle(target.width, center, mousePosition))
alert('Foo');
}
<img onmouseover="intersects(this, event)" src="circle.png" />