html5-canvas javascript draw line with slider - javascript

As I move my slider I am drawing an arc. I have made it dynamic. If I change the points of arc then the line drawn will also change. Same thing I want to do with a line. If I move my slider the line should get drawn. Also I want to make it dynamic means If i change the line points the line should also change.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>CH5EX10: Moving In A Simple Geometric Spiral </title>
<style>
.wrapper {
margin: 0 auto;
width: 1000px;
}
.uppleft {
float: left;
width: 1000px;
position: relative;
margin: 0 0 500px 10px;
}
.dnleft {
float: left;
width: 1000px;
}
.clear {
clear: both;
}
</style>
</head>
<body>
<div class="wrapper">
<div class="uppleft">
<canvas id="canvasOne" width="300" height="300"width="500" height="500" style="position:absolute; left:5px; top:10px; border:1px solid red;">
Your browser does not support HTML5 Canvas.
</canvas>
<canvas id="canvasTwo" width="300" height="300" style="position:absolute; left:250px; top:30px; border:1px solid red;">
Your browser does not support HTML5 Canvas.
</canvas>
</div>
<div class="clear"></div>
<div class="dnleft">
<input id="slide1" type="range" min="0" max="100" step="1" value="0" onchange="counterSliderNew('slide1', '100');"/>
</div>
</div>
</body>
<script type="text/javascript">
drawSlopeCurve2('canvasTwo', 16, 170, 200, 80)
function counterSliderNew(sID, maxValue) {
var slideVal = document.getElementById(sID).value;
//alert(slideVal);
if (maxValue == 100) {
slideVal = slideVal / 100;
}
if (slideVal == 0) {
} else if (slideVal > 0 && slideVal <= 34) {
erase('canvasOne');
drawBezier2('canvasOne', new Array({
x : 18.8,
y : 75
}, {
x : 28,
y : 160
}, {
x : 228,
y : 165
}), slideVal);
} else if (slideVal > 34 && slideVal <= 67) {
//alert(slideVal);
erase('canvasOne');
drawBezier2('canvasOne', new Array({
x : 18.8,
y : 75
}, {
x : 28,
y : 160
}, {
x : 228,
y : 165
}), slideVal);
staticGraph5('canvasTwo');
} else if (slideVal > 67 && slideVal <= 100) {
erase('canvasOne');
drawBezier2('canvasOne', new Array({
x : 18.8,
y : 75
}, {
x : 28,
y : 160
}, {
x : 228,
y : 165
}), slideVal);
}
}
function drawBezier2(canId, points, slideVal) {
var canvas = document.getElementById(canId);
var context = canvas.getContext("2d");
// Draw guides
context.lineWidth = 2;
context.strokeStyle = "rgb(113, 113, 213)";
context.beginPath();
// Label end points
context.fillStyle = "rgb(0, 0, 0)";
// Draw spline segemnts
context.moveTo(points[0].x, points[0].y);
for (var t = 0; t <= slideVal; t += 0.1) {
context.lineTo(Math.pow(1 - t, 2) * points[0].x + 2 * (1 - t) * t * points[1].x + Math.pow(t, 2) * points[2].x, Math.pow(1 - t, 2) * points[0].y + 2 * (1 - t) * t * points[1].y + Math.pow(t, 2) * points[2].y);
}
// Stroke path
context.stroke();
}
function erase(canvasId) {
var canvas = document.getElementById(canvasId);
var context = canvas.getContext("2d");
context.beginPath();
context.clearRect(0, 0, canvas.width, canvas.height);
canvas.width = canvas.width;
}
function drawSlopeCurve2(canId, mvx, mvy, lnx, lny) {
var canvas = document.getElementById(canId);
var context = canvas.getContext('2d');
context.beginPath();
context.moveTo(mvx, mvy);
context.lineTo(lnx, lny);
context.lineWidth = 0.6;
context.stroke();
}
</script>
</html>
This will work only in chrome. I want to use drawSlopeCurve2('canvasTwo', 16, 170, 200, 80); this function to draw a line on movement of slider. I am looking for some formula as I have used for moving an arc on slider movement.

You can use this function to get an array of points that interpolate a line between any 2 points:
function linePoints(x1, y1, x2, y2, frames) {
var dx = x2 - x1;
var dy = y2 - y1;
var length = Math.sqrt(dx * dx + dy * dy);
var incrementX = dx / frames;
var incrementY = dy / frames;
var a = new Array();
a.push({ x: x1, y: y1 });
for (var frame = 0; frame < frames - 1; frame++) {
a.push({
x: x1 + (incrementX * frame),
y: y1 + (incrementY * frame)
});
}
a.push({ x: x2, y: y2 });
return (a);
}
Here is code and a Fiddle: http://jsfiddle.net/m1erickson/qhzJv/
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>CH5EX10: Moving In A Simple Geometric Spiral </title>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<style>
.wrapper {
width: 700px;
height:350px;
border:2px solid green;
padding:15px;
}
.uppleft{
display: inline;
margin-left: 30px;
}
canvas{
border:1px solid red;
}
#sliderwrapper{
display: inline-block;
position:relative;
width:37px; height:300px;
border:1px solid blue;
}
#amount{
position:absolute;
left:5px; top:5px;
margin-bottom:15px;
width:23px;
border:0; color:#f6931f;
font-weight:bold;
}
#slider-vertical{
position:absolute;
left:10px; top:40px;
width:15px; height:225px;
border:0px; color:#f6931f;
font-weight:bold;
}
</style>
</head>
<body>
<div class="wrapper">
<div id="sliderwrapper">
<input type="text" id="amount" />
<div id="slider-vertical"></div>
</div>
<div class="uppleft">
<canvas id="canvasOne" width="300" height="300">
Your browser does not support HTML5 Canvas.
</canvas>
<canvas id="canvasTwo" width="300" height="300">
Your browser does not support HTML5 Canvas.
</canvas>
</div>
</div>
</body>
<script type="text/javascript">
var startingValue=20;
// handles user moving the slider
$( "#slider-vertical" ).slider({
orientation: "vertical",
range: "min",
min: 0,
max: 100,
value: startingValue,
slide: function( event, ui ) {
$( "#amount" ).val( ui.value );
counterSliderNew('slide1', '100', ui.value);
}
});
// get an array of 100 points between start and end of line
var points=linePoints(16, 170, 200, 80,100);
// draw the initial point based on the beginning slider value
counterSliderNew('slide1', '100', startingValue);
function counterSliderNew(sID, maxValue,theSliderValue) {
var slideVal = theSliderValue; // document.getElementById(sID).value;
// get the slider value and get the point at points[slideVal]
var point=points[slideVal];
erase('canvasTwo');
drawSlopeCurve2('canvasTwo',16,170,point.x,point.y);
if (maxValue == 100) {
slideVal = slideVal / 100;
}
if (slideVal == 0) {
} else if (slideVal > 0 && slideVal <= 34) {
erase('canvasOne');
drawBezier2('canvasOne', new Array({
x : 18.8,
y : 75
}, {
x : 28,
y : 160
}, {
x : 228,
y : 165
}), slideVal);
} else if (slideVal > 34 && slideVal <= 67) {
//alert(slideVal);
erase('canvasOne');
drawBezier2('canvasOne', new Array({
x : 18.8,
y : 75
}, {
x : 28,
y : 160
}, {
x : 228,
y : 165
}), slideVal);
staticGraph5('canvasTwo');
} else if (slideVal > 67 && slideVal <= 100) {
erase('canvasOne');
drawBezier2('canvasOne', new Array({
x : 18.8,
y : 75
}, {
x : 28,
y : 160
}, {
x : 228,
y : 165
}), slideVal);
}
}
function drawBezier2(canId, points, slideVal) {
var canvas = document.getElementById(canId);
var context = canvas.getContext("2d");
// Draw guides
context.lineWidth = 2;
context.strokeStyle = "rgb(113, 113, 213)";
context.beginPath();
// Label end points
context.fillStyle = "rgb(0, 0, 0)";
// Draw spline segemnts
context.moveTo(points[0].x, points[0].y);
for (var t = 0; t <= slideVal; t += 0.1) {
context.lineTo(Math.pow(1 - t, 2) * points[0].x + 2 * (1 - t) * t * points[1].x + Math.pow(t, 2) * points[2].x, Math.pow(1 - t, 2) * points[0].y + 2 * (1 - t) * t * points[1].y + Math.pow(t, 2) * points[2].y);
}
// Stroke path
context.stroke();
}
function erase(canvasId) {
var canvas = document.getElementById(canvasId);
var context = canvas.getContext("2d");
context.beginPath();
context.clearRect(0, 0, canvas.width, canvas.height);
canvas.width = canvas.width;
}
function drawSlopeCurve2(canId, mvx, mvy, lnx, lny) {
var canvas = document.getElementById(canId);
var context = canvas.getContext('2d');
context.beginPath();
context.moveTo(mvx, mvy);
context.lineTo(lnx, lny);
context.lineWidth = 0.6;
context.stroke();
}
function linePoints(x1, y1, x2, y2, frames) {
var dx = x2 - x1;
var dy = y2 - y1;
var length = Math.sqrt(dx * dx + dy * dy);
var incrementX = dx / frames;
var incrementY = dy / frames;
var a = new Array();
a.push({ x: x1, y: y1 });
for (var frame = 0; frame < frames - 1; frame++) {
a.push({
x: x1 + (incrementX * frame),
y: y1 + (incrementY * frame)
});
}
a.push({ x: x2, y: y2 });
return (a);
}
</script>
</html>

Related

Why HTML canvas collision is not happening for the ball and the paddle?

I am building my ping pong game with javascript, Canvas and HTML So here is my Javascript code below to create the paddle and the ball. I want to know how to make the collision happen between paddle and ball. Below are my javascript and HTML
Below is my HTML code. Here I am declaring the canvas element
var c = document.getElementById("frame");
c.width = window.innerWidth * 0.31;
c.height = window.innerHeight * 0.55;
var ctx = c.getContext("2d");
var x = 10;
var y = 10;
var rx = 10;
var ry = 400;
var height = 70;
var width = 12;
var radius = 10;
var vx = Math.floor(Math.random() * 2);
var vy = Math.floor(Math.random() * 4);
drawPad(rx, ry, height, width);
function drawPad(rx, ry, height, width) {
ctx.fillStyle = "#f2a34b";
ctx.fillRect(rx, ry, height, width);
}
function drawCircle() {
ctx.beginPath();
ctx.arc(x, y, radius, 0, 2 * Math.PI);
ctx.closePath();
ctx.stroke();
ctx.fill();
}
function moveCircle() {
requestAnimationFrame(moveCircle);
if ((x + radius > 500) || (x - radius < 0)) {
vx = 0 - vx;
}
if ((y + radius > 420) || (y - radius < 0)) {
vy = 0 - vy;
}
x = x + vx;
y = y + vy;
ctx.clearRect(0, 0, 500, 500);
drawPad(rx, ry, height, width);
drawCircle();
}
moveCircle();
window.onkeydown = function(event) {
if (event.keyCode == 37 && rx > 20) {
rx = rx - 20;
} else if (event.keyCode == 39 && rx <= 420) {
rx = rx + 20;
}
ctx.clearRect(0, 0, 500, 500);
drawPad(rx, ry, height, width);
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style type="text/css">
canvas {
border: 1px solid #c7c7c7;
background-color: rgb(175, 166, 166);
}
</style>
</head>
<body>
<canvas id="frame"></canvas>
<script src="canvas.js"></script>
</body>
</html>
I only see you verify the collision with the borders in your code, but not with the paddle itself.
You just need to add some condition to detect its collision with the paddle. If a collision happened then the ball will move up otherwise it moves down
if(y+radius>=ry)
{
moveUp = true;
moveDown = false;
}
if(y+radius<=0)
{
moveUp = false;
moveDown = true;
}
and later tell the programe how it will happen
if(moveUp){
//x = x + vx;
y = y - vy;
}
if(moveDown){
//x = x - vx;
y = y + vy;
}
which gives you something like that if i am not mistaken :
var c = document.getElementById("frame");
c.width = window.innerWidth * 0.31;
c.height = window.innerHeight * 0.55;
var ctx = c.getContext("2d");
var x = 10;
var y = 10;
var rx = 10;
var ry = (window.innerHeight*0.55)-10;
var height = 70;
var width = 12;
var radius = 10;
var vx = Math.floor(Math.random() * 2);
var vy = Math.floor(Math.random() * 4);
let moveUp = false;
let moveDown = true;
drawPad(rx, ry, height, width);
function drawPad(rx, ry, height, width) {
ctx.fillStyle = "#f2a34b";
ctx.fillRect(rx, ry, height, width);
}
function drawCircle() {
ctx.beginPath();
ctx.arc(x, y, radius, 0, 2 * Math.PI);
ctx.closePath();
ctx.stroke();
ctx.fill();
}
function moveCircle() {
requestAnimationFrame(moveCircle);
/*if ((x + radius > 500) || (x - radius < 0)) {
vx = 0 - vx;
}*/
if((x+radius>=rx)&&(y+radius>=ry))
{
moveUp = true;
moveDown = false;
}
if(y+radius<=0)
{
moveUp = false;
moveDown = true;
}
/*if ((y + radius > 420) || (y - radius < 0)) {
vy = 0 - vy;
}*/
if(moveUp){
//x = x + vx;
y = y - vy;
}
if(moveDown){
//x = x - vx;
y = y + vy;
}
ctx.clearRect(0, 0, 500, 500);
drawPad(rx, ry, height, width);
drawCircle();
}
moveCircle();
window.onkeydown = function(event) {
if (event.keyCode == 37 && rx > 20) {
rx = rx - 20;
} else if (event.keyCode == 39 && rx <= 420) {
rx = rx + 20;
}
ctx.clearRect(0, 0, 500, 500);
drawPad(rx, ry, height, width);
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style type="text/css">
canvas {
border: 1px solid #c7c7c7;
background-color: rgb(175, 166, 166);
}
</style>
</head>
<body>
<canvas id="frame"></canvas>
<script src="canvas.js"></script>
</body>
</html>

clickable object or shape inside a canvas viewbox window

<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
<style>
body {
font-family: "Lato", sans-serif;
}
.sidenav {
height: 100%;
width: 0;
position: fixed;
z-index: 1;
top: 0;
left: 0;
background-color: #111;
overflow-x: hidden;
transition: 0.5s;
padding-top: 60px;
}
.sidenav a {
padding: 8px 8px 8px 32px;
text-decoration: none;
font-size: 25px;
color: #818181;
display: block;
transition: 0.3s;
}
.sidenav a:hover {
color: #f1f1f1;
}
.sidenav .closebtn {
position: absolute;
top: 0;
right: 25px;
font-size: 36px;
margin-left: 50px;
}
#main {
transition: margin-left .5s;
padding: 16px;
}
#media screen and (max-height: 450px) {
.sidenav {padding-top: 15px;}
.sidenav a {font-size: 18px;}
}
</style>
</head>
<body>
<div id="mySidenav" class="sidenav">
×
About
Services
Clients
Contact
</div>
<div id="main">
<span style="font-size:30px;cursor:pointer" onclick="openNav()">☰ Menu</span>
<canvas id="canvas" width="600" height="350" style="border:2px solid #d3d3d3;">></canvas>
</div>
<script>
var zoomIntensity = 0.1;
var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");
var width = 90;
var height = 50;
var scale = 1;
var originx = 0;
var originy = 0;
var visibleWidth = width;
var visibleHeight = height;
var c = document.getElementById("canvas");
var ctx = c.getContext("2d");
function draw(){
context.fillStyle = "white";
context.fillRect(originx,originy,1000/scale,800/scale);
context.fillStyle = "blue";
context.fillRect(170,50,50,50);
context.fillStyle = "white";
context.fillText('click here',175,70);
}
setInterval(draw, 1000/60);
canvas.onwheel = function (event){
event.preventDefault();
var mousex = event.clientX - canvas.offsetLeft;
var mousey = event.clientY - canvas.offsetTop;
var wheel = event.deltaY < 0 ? 1 : -1;
var zoom = Math.exp(wheel*zoomIntensity);
context.translate(originx, originy);
originx -= mousex/(scale*zoom) - mousex/scale;
originy -= mousey/(scale*zoom) - mousey/scale;
context.scale(zoom, zoom);
context.translate(-originx, -originy);
scale *= zoom;
visibleWidth = width / scale;
visibleHeight = height / scale;
}
function openNav() {
document.getElementById("mySidenav").style.width = "200px";
document.getElementById("main").style.marginLeft = "200px";
}
function closeNav() {
document.getElementById("mySidenav").style.width = "0";
document.getElementById("main").style.marginLeft= "0";
}
</script>
</body>
</html>
is there away to make a shape or object clickable on canvas frame or viewbox, even when i zoom in or out, cause all the examples i saw was just a fixed clickable location. for instance google map locations when i zoom in i can click more objects.
is there away to make a shape or object clickable on canvas frame or viewbox, even when i zoom in or out, cause all the examples i saw was just a fixed clickable location. for instance google map locations when i zoom in i can click more objects.
There are two spaces you have to account for, the actual canvas space and the translated space. This means you need to translate the mouse coordinates in order to know where in the space the object is actually located and map it back to the canvas coordinates so you can know if you are clicking on it. This is achieved by keeping track of the offset value you provided in the var originx, but the problem is that there is no way based on my trails at least for you to translate the mouse click location if you use the context.translate(originx, originy) if you both scale and pan the object space.
I have rewritten the code without the use of the translate function by making my own translate function that enables you to translate between the canvas space and object space in order to register a click event on the object regardless of the panned or zoomed in location.
This function also has a click to pan feature so you can click and drag the object screen to where ever you want to object to be positioned.
/*jshint esversion: 8 */
(function() {
const canvas = document.querySelector("canvas");
const context = canvas.getContext("2d");
let canvasWidth = 600;
let canvasHeight = 600;
let offset = {
x: 0,
y: 0
};
let pan = {
x: 0,
y: 0
};
var zoomIntensity = 0.1;
let scale = 1;
let mouse = {
x: 0,
y: 0
};
let dragging = false;
let square;
let shapes = [{
x: 170,
y: 50,
w: 50,
h: 50,
color: "blue"
},
{
x: 85,
y: 25,
w: 50,
h: 50,
color: "red"
},
{
x: 50,
y: 100,
w: 50,
h: 50,
color: "green"
},
];
function init() {
canvas.width = canvasWidth;
canvas.height = canvasHeight;
renderCanvas();
}
function drawSquare(x, y, width, height, color) {
context.fillStyle = color;
context.fillRect(x, y, width, height);
}
function objectsToCanvasScreen(x, y) {
const canvasScreenX = Math.floor((x - offset.x) * scale);
const canvasScreenY = Math.floor((y - offset.y) * scale);
return {
x: canvasScreenX,
y: canvasScreenY
};
}
function canvasToObjectsScreen(x, y) {
return {
x: x / scale + offset.x,
y: y / scale + offset.y
};
}
function renderCanvas() {
context.clearRect(0, 0, canvas.width, canvas.height);
shapes.forEach(({
x,
y,
w,
h,
color
}, index) => {
const {
x: csx,
y: csy
} = objectsToCanvasScreen(x, y);
shapes[index]._x = csx;
shapes[index]._y = csy;
shapes[index]._w = w * scale;
shapes[index]._h = h * scale;
drawSquare(csx, csy, w * scale, h * scale, color);
});
}
canvas.onwheel = function(e) {
const zoom = Math.exp((e.deltaY < 0 ? 1 : -1) * zoomIntensity);
const beforeZoom = canvasToObjectsScreen(mouse.x, mouse.y);
scale *= zoom;
const afterZoom = canvasToObjectsScreen(mouse.x, mouse.y);
offset.x += beforeZoom.x - afterZoom.x;
offset.y += beforeZoom.y - afterZoom.y;
renderCanvas();
};
canvas.onmousedown = function(e) {
if (e.button === 0) {
pan.x = mouse.x;
pan.y = mouse.y;
dragging = true;
}
};
canvas.onmouseup = (e) => (dragging = false);
canvas.onmousemove = function(e) {
mouse.x = e.offsetX;
mouse.y = e.offsetY;
if (dragging) {
offset.x -= (mouse.x - pan.x) / scale;
offset.y -= (mouse.y - pan.y) / scale;
pan.x = mouse.x;
pan.y = mouse.y;
renderCanvas();
}
};
canvas.onclick = function(e) {
shapes.forEach(({
_x,
_y,
_w,
_h,
color
}) => {
const {
x: mousex,
y: mousey
} = canvasToObjectsScreen(mouse.x, mouse.y);
const {
x: squarex,
y: squarey
} = canvasToObjectsScreen(_x, _y);
if (
mousex >= squarex &&
mousex <= _w / scale + squarex &&
mousey >= squarey &&
mousey <= _h / scale + squarey
) {
alert(`${color} clicked!`);
}
});
};
init();
})();
body {
font-family: "Lato", sans-serif;
}
#canvas {
background: #E1BC8B;
}
<body>
<div id="main">
<canvas id="canvas" width="300" height="350"></canvas>
</div>
</body>

How can I make canvas element act as a background?

I want to use the canvas element as the background for my page.
How can I make "We craft brand experiences for companies and nonprofits making a difference." show up on top of the background?
<!DOCTYPE html>
<html >
<head>
<meta charset="UTF-8">
<title>Confetti Party</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/meyer-reset/2.0/reset.min.css">
</head>
<body>
<canvas id="canvas"></canvas>
<script src="js/index.js"></script>
<h1>we craft brand experiences for companies and nonprofits making a difference. </h1>
</body>
</html>
As you can see, my h1 tag is not on top of background.
If I understand your question correctly, then you effectively want to make the canvas your page's background. This is rather trivial can be done by taking advantage of the CSS z-index property:
///////////////////////////////////////////////
// configurables
///////////////////////////////////////////////
// background color
// var bg = [159, 240, 167]
var bg = [255, 255, 225]
// maximum number of particles present at any time
var num_particles = 150
// chace of split
var chance_birth = 0.37
// chance of termination/death
var chance_death = 0.38
var cols = ['#FF5722', '#FF9800', '#FF9800', '#FF9800', '#FF9800', '#B71C1C', '#00BCD4', '#00BCD4', '#009688']
///////////////////////////////////////////////
// the other stuff
///////////////////////////////////////////////
//var canvas = document.createElement("canvas")
//document.getElementsByTagName("body")[0].appendChild(canvas)
var canvas = document.getElementById("canvas")
var ctx = canvas.getContext("2d")
var particles = []
var step = 0
var step_max = 360
setup()
window.addEventListener("resize", setup)
function setup() {
canvas.width = window.innerWidth
canvas.height = window.innerHeight
fill(1)
}
function fill(amt) {
ctx.beginPath();
ctx.rect(0, 0, canvas.width, canvas.height)
ctx.fillStyle = `rgba(${bg[0]}, ${bg[1]}, ${bg[2]}, ${amt})`
ctx.fill()
}
setInterval(animate, 1000/60)
// window.requestAnimationFrame(animate);
function animate() {
fill(0.01)
step = (step + 1) % step_max
draw()
// window.requestAnimationFrame(function(){animate()})
}
function getRandCol () {
return cols[Math.floor(Math.random() * cols.length)]
}
function draw() {
var pad = 0.02
var p
if (particles.length < num_particles && step % 2 === 0) {
var x = (Math.random() * (1 - pad * 2) + pad) * canvas.width
var y = canvas.height + Math.random()*10 //(Math.random() * (1 - pad * 2) + pad) * canvas.height
p = new Particle(x, y, ctx)
particles.push(p)
}
var i
for (i = 0; i < particles.length; i++) {
particles[i].update()
particles[i].draw()
// branch-birth
if (step % 4 === 0 && Math.random() < chance_birth && particles.length < num_particles) {
var x = particles[i].x
var y = particles[i].y
p = new Particle(x, y, ctx)
p.color = particles[i].color
particles.push(p)
}
}
// death
for (i = particles.length -1 ; i >= 0; i--) {
p = particles[i]
if ((step % 4 === 0 && Math.random() < chance_death) || p.y < -20 || p.x < -20 || p.x > canvas.width + 20) {
particles.splice(i, 1)
}
}
// draw links
var dist_max = 60
for (i = particles.length -1 ; i >= 0; i--) {
p = particles[i]
}
}
function Particle (x, y, ctx) {
this.x = x
this.y = y
this.px = x
this.py = y
this.dx_min = -20
this.dx_max = 20
this.dy_min = -1
this.dy_max = -25
this.s = 0.8
this.ctx = ctx
this.color = getRandCol() //"#ee9977"
this.update = function () {
this.px = this.px * this.s + this.x * (1 - this.s)
this.py = this.py * this.s + this.y * (1 - this.s)
var dxy = this.dxy()
this.x = this.s * this.x + (Math.random() * dxy.dx + this.x) * (1 - this.s)
this.y = this.s * this.y + (Math.random() * dxy.dy + this.y) * (1 - this.s)
}
this.draw = function () {
// var v = Math.min(this.vsq(), 500)
ctx.lineWidth = 2 //Math.sqrt(v)/3
ctx.beginPath()
ctx.moveTo(this.px, this.py)
ctx.strokeStyle = this.color
ctx.lineTo(this.x, this.y)
ctx.lineCap = "round"
ctx.stroke()
}
this.dxy = function () {
var dx = (this.dx_max - this.dx_min) * Math.random() + this.dx_min
var dy = (this.dy_max - this.dy_min) * Math.random() + this.dy_min
return {dx, dy}
}
this.vsq = function () {
var x = this.px - this.x
var y = this.py - this.y
return x * x + y * y
}
}
canvas{
/* Move the canvas to a low z-index (background) */
z-index: -1;
}
.wrapup{
/* This class creates a div that is positioned on top of everything outside of it */
width:100%;
height:100%;
z-index:100;
display:block;
overflow:hidden;
margin:0;
border:0;
padding:0;
position:absolute;
top:0;
bottom:0;
right:0;
left:0;
}
body {
/* Just some stuff to clean up the look by filling page and removing scrollbars */
width:100%;
height: 100%;
overflow: hidden;
}
<!DOCTYPE html>
<html >
<head>
<meta charset="UTF-8">
<title>Confetti Party</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/meyer-reset/2.0/reset.min.css">
</head>
<body>
<canvas id="canvas"></canvas>
<script src="js/index.js"></script>
<div class="wrapup">
<h1>we craft brand experiences for companies and nonprofits making a difference. </h1>
</div>
</body>
</html>
As for how you decide to position the h1 on the page, that is up to you, but anything you place inside of the wrapup div will appear atop the canvas.
Change <h1> to
<h1 style="position:fixed; top:500px; left:300px;">
You can adjust the 500px and 300px values to move it to a different position on the screen. You can also use a combination of % and margin to automatically center the element, for example:
top:50%; margin-top:-6em;
If you want the text to scroll down with the page, use position:absolute instead.

Collision between two elements with rotating

var keys = new Array();
var direction;
var direction;
var iNr = 0;
$(document).ready(function(){
looper();
$("#demo1").css("margin-top", 400 + "px");
$("#demo2").css("margin-left", 380 + "px");
myFunction();
});
function myFunction()
{
iNr = iNr + 0.5;
$("#main").css("transition","all 0.1s");
$("#main").css("transform","rotate(" + iNr + "deg)");
setTimeout(function()
{
myFunction();
}, 50);
}
function looper()
{
var p =$("#circle");
var offset = p.offset();
var t =$(".red");
var roffset = t.offset();
var rect1 = {x: offset.left, y: offset.top, width: p.width(), height: p.height()}
var rect2 = {x: roffset.left, y: roffset.top, width: t.width(), height: t.height()}
if (rect1.x < rect2.x + rect2.width && rect1.x + rect1.width > rect2.x && rect1.y < rect2.y + rect2.height && rect1.height + rect1.y > rect2.y) {
console.log("now");
}
if(direction == "left")
{
if(offset.left - 50 > 0)
{
$("#circle").css("left", ($("#circle").position().left - 2) + "px");
}
}
if(direction == "up")
{
if(offset.top - 50 > 0)
{
$("#circle").css("top", ($("#circle").position().top - 2) + "px");
}
}
if(direction == "right")
{
if((offset.left + 50) < $(window).width())
{
$("#circle").css("left", ($("#circle").position().left + 2) + "px");
}
}
if(direction == "down")
{
if((offset.top + 50) < $(window).height())
{
$("#circle").css("top", ($("#circle").position().top + 2) + "px");
}
}
ID=window.setTimeout("looper();", 1);
}
$(document).keyup(function(event) {
if (event.keyCode == 37)
{
var index = keys.indexOf("37");
keys.splice(index, 1);
direction = "";
}
if (event.keyCode == 38)
{
var index = keys.indexOf("38");
keys.splice(index, 1);
direction = "";
}
if (event.keyCode == 39)
{
var index = keys.indexOf("39");
keys.splice(index, 1);
direction = "";
}
if (event.keyCode == 40)
{
var index = keys.indexOf("40");
keys.splice(index, 1);
direction = "";
}
});
$(document).keydown(function(event) {
if (event.keyCode == 37)
{
keys.push("37");
direction = "left";
}
if (event.keyCode == 38)
{
keys.push("38");
direction = "up";
}
if (event.keyCode == 39)
{
keys.push("39");
direction = "right";
}
if (event.keyCode == 40)
{
keys.push("40");
direction = "down";
}
});
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>test</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<body style="background-color:black; overflow-y:scroll;">
<div style="width:400px; margin-left:500px; height:400px;" id="main">
<div id="demo1" style="width:400px; height:20px; background-color:red; position:absolute;" class="red test all"></div>
<div id="demo2" style="width:20px; height:400px; background-color:yellow; position:absolute;" class="test all"></div>
<div id="demo3" style="width:400px; height:20px; background-color:blue; position:absolute;" class="test all"></div>
<div id="demo4" style="width:20px; height:400px; background-color:green; position:absolute;" class="test all"></div>
</div>
<div style="width:25px; height:25px; background-color:white; position:absolute; border-radius:50%;" id="circle"></div>
</body>
</html>
I have programmed a game.
In this game my function checks, whether there is a collision between div1 and div2.
Or if they are overlapping or so... how you want to spell it.
Without a rotation everything is ok.
But now i have a problem.
I want to rotate div2 with transform:rotate(Xdeg);
but if I do this my calculation for the collision dosen't work.
I use this:
var rect1 = {x: 5, y: 5, width: 50, height: 50}
var rect2 = {x: 20, y: 10, width: 10, height: 10}
if (rect1.x < rect2.x + rect2.width && rect1.x + rect1.width > rect2.x && rect1.y < rect2.y + rect2.height && rect1.height + rect1.y > rect2.y) {
// collision detected!
}
do you have any ideas to solve this problem?
Thanks for helping :-)
There are several ways to do this. This example just guides you of how it could be done with rectangles.
These are the steps that are done here:
You have to calculate the position of all rotated corners of all rectangles that you want to check whether they are being collided. To get these rotated corners, you can use several methods. In this example 2d-vectors and a 2d-rotation-matrix are used:
a vector that has its origin in the center of a rectangle and directs to the top-left-corner(x,y) of a rectangle:
var center = {
x: x + width / 2,
y: y + height / 2
};
var vector = {
x: (x - center.x),
y: (y - center.y)
};
multiply this vector with a rotation-matrix to rotate this vector:
// modified sin function to calulcate sin in the unit degrees instead of radians
function sin(x) {
return Math.sin(x / 180 * Math.PI);
}
// modified cos function
function cos(x) {
return Math.cos(x / 180 * Math.PI);
}
var rotationMatrix = [[cos(angle), -sin(angle)],[sin(angle), cos(angle)]];
var rotatedVector = {
x: vector.x * rotationMatrix[0][0] + vector.y * rotationMatrix[0][1],
y: vector.x * rotationMatrix[1][0] + vector.y * rotationMatrix[1][1]
};
And finally get the rotated top-left-corner, you can start from the center of a rectangle and go to where the rotated vector points to. This is where top-left-corner is located after rotation:
{
x: (center.x + rotatedVector.x),
y: (center.y + rotatedVector.y)
}
All the steps described above are done by getRotatedTopLeftCornerOfRect and must be done with all other corners as well. Before the location of the next
corner (right-top) can be calculated next vector must be calulcated that points to this corner. To get the next vector that points to the top-right-corner the angle between the first vector (left-top) and the second vector (right-top) is calculated. The third vector points to the right-bottom-corner when its angle is incremended by the first angle and the second angle and the fourth vector is rotated by an angle that is summed up the first, second and third angle. All of this is done in the setCorners-method and this image shows this process partly:
To detect a collision there are tons of algorithms. In this example the Point in polygon algorithm is used to check each rotated corner of a rectangle whether a corner is with the border or within another rectangle, if so, then the method isCollided returns true. The Point in polygon algorithm is used in pointInPoly and can also be found here.
Combining all of the steps described above was tricky, but it works with all rectangles of all sizes and the best of all you can test it right here without a library by clicking on "Run code snippet".
(tested browsers: FF 50.1.0, IE:10-EDGE, Chrome:55.0.2883.87 m):
var Rectangle = (function () {
function sin(x) {
return Math.sin(x / 180 * Math.PI);
}
function cos(x) {
return Math.cos(x / 180 * Math.PI);
}
function getVectorLength(x, y, width, height){
var center = {
x: x + width / 2,
y: y + height / 2
};
//console.log('center: ',center);
var vector = {
x: (x - center.x),
y: (y - center.y)
};
return Math.sqrt(vector.x*vector.x+vector.y*vector.y);
}
function getRotatedTopLeftCornerOfRect(x, y, width, height, angle) {
var center = {
x: x + width / 2,
y: y + height / 2
};
//console.log('center: ',center);
var vector = {
x: (x - center.x),
y: (y - center.y)
};
//console.log('vector: ',vector);
var rotationMatrix = [[cos(angle), -sin(angle)],[sin(angle), cos(angle)]];
//console.log('rotationMatrix: ',rotationMatrix);
var rotatedVector = {
x: vector.x * rotationMatrix[0][0] + vector.y * rotationMatrix[0][1],
y: vector.x * rotationMatrix[1][0] + vector.y * rotationMatrix[1][1]
};
//console.log('rotatedVector: ',rotatedVector);
return {
x: (center.x + rotatedVector.x),
y: (center.y + rotatedVector.y)
};
}
function getOffset(el) {
var _x = 0;
var _y = 0;
while (el && !isNaN(el.offsetLeft) && !isNaN(el.offsetTop)) {
_x += el.offsetLeft - el.scrollLeft;
_y += el.offsetTop - el.scrollTop;
el = el.offsetParent;
}
return {
top: _y,
left: _x
};
}
function pointInPoly(verties, testx, testy) {
var i,
j,
c = 0
nvert = verties.length;
for (i = 0, j = nvert - 1; i < nvert; j = i++) {
if (((verties[i].y > testy) != (verties[j].y > testy)) && (testx < (verties[j].x - verties[i].x) * (testy - verties[i].y) / (verties[j].y - verties[i].y) + verties[i].x))
c = !c;
}
return c;
}
function Rectangle(htmlElement, width, height, angle) {
this.htmlElement = htmlElement;
this.width = width;
this.height = height;
this.setCorners(angle);
}
function testCollision(rectangle) {
var collision = false;
this.getCorners().forEach(function (corner) {
var isCollided = pointInPoly(rectangle.getCorners(), corner.x, corner.y);
if (isCollided) collision = true;
});
return collision;
}
function checkRectangleCollision(rect, rect2) {
if (testCollision.call(rect, rect2)) return true;
else if (testCollision.call(rect2, rect)) return true;
return false;
}
function getAngleForNextCorner(anc,vectorLength) {
var alpha = Math.acos(anc/vectorLength)*(180 / Math.PI);
return 180 - alpha*2;
}
Rectangle.prototype.setCorners = function (angle) {
this.originalPos = getOffset(this.htmlElement);
this.leftTopCorner = getRotatedTopLeftCornerOfRect(this.originalPos.left, this.originalPos.top, this.width, this.height, angle);
var vecLength = getVectorLength(this.originalPos.left, this.originalPos.top, this.width, this.height);
//console.log('vecLength: ',vecLength);
angle = angle+getAngleForNextCorner(this.width/2, vecLength);
//console.log('angle: ',angle);
this.rightTopCorner = getRotatedTopLeftCornerOfRect(this.originalPos.left, this.originalPos.top, this.width, this.height, angle);
angle = angle+getAngleForNextCorner(this.height/2, vecLength);
//console.log('angle: ',angle);
this.rightBottomCorner = getRotatedTopLeftCornerOfRect(this.originalPos.left, this.originalPos.top, this.width, this.height, angle);
angle = angle+getAngleForNextCorner(this.width/2, vecLength);
//console.log('angle: ',angle);
this.leftBottomCorner = getRotatedTopLeftCornerOfRect(this.originalPos.left, this.originalPos.top, this.width, this.height, angle);
//console.log(this);
};
Rectangle.prototype.getCorners = function () {
return [this.leftTopCorner,
this.rightTopCorner,
this.rightBottomCorner,
this.leftBottomCorner];
};
Rectangle.prototype.isCollided = function (rectangle) {
return checkRectangleCollision(this, rectangle);
};
return Rectangle;
}) ();
var rotA = 16;
var widthA = 150;
var heightA = 75;
var htmlRectA = document.getElementById('rectA');
var rotB = 28.9;
var widthB = 50;
var heightB = 130;
var htmlRectB = document.getElementById('rectB');
var msgDiv = document.getElementById('msg');
var rectA = new Rectangle(htmlRectA, widthA, heightA, rotA);
var rectB = new Rectangle(htmlRectB, widthB, heightB, rotB);
window.requestAnimFrame = function(){
return window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame;
}();
function draw(){
rotA+=1.2;
htmlRectA.setAttribute('style','-ms-transform: rotate('+rotA+'deg);-webkit-transform: rotate('+rotA+'deg);transform: rotate('+rotA+'deg)');
rotB+=5.5;
htmlRectB.setAttribute('style','-ms-transform: rotate('+rotB+'deg);-webkit-transform: rotate('+rotB+'deg);transform: rotate('+rotB+'deg)');
rectA.setCorners(rotA);
rectB.setCorners(rotB);
if(rectA.isCollided(rectB)){
msgDiv.innerHTML = 'Collision detected!';
msgDiv.setAttribute('style','color: #FF0000');
}
else {
msgDiv.innerHTML = 'No Collision!';
msgDiv.setAttribute('style','color: #000000');
}
setTimeout(function(){
window.requestAnimFrame(draw);
},50);
}
window.requestAnimFrame(draw);
#rectA{
background-color: #0000FF;
width:150px;
height:75px;
position:absolute;
top:60px;
left:180px;
-ms-transform: rotate(16deg);
-webkit-transform: rotate(16deg);
transform: rotate(16deg);
}
#rectB{
background-color: #FF0000;
width:50px;
height:130px;
position:absolute;
top:140px;
left:250px;
-ms-transform: rotate(28.9deg);
-webkit-transform: rotate(28.9deg);
transform: rotate(28.9deg);
}
<div id="rectA">A</div>
<div id="rectB">B</div>
<div id="msg"></div>

html5-canvas move object on line

I want to move a object on a slanting line. I have given my code. In my code in my 3rd div as I move the slider I am drawing a slanting line on this line I want to move an object. Similar thing I am doing in my 1st div. Where I am moving an object on curve. I am looking for some function in which I will provide the points and the object will follow the points. Here is my code. This code works only in chrome as I am trying to make this only for safari and chrome browsers.
<!DOCTYPE HTML>
<html>
<head>
<style type="text/css">
.wrapper {
margin: 0 auto;
width: 1000px;
}
.canHdr {
float: left;
width: 450px;
height: 400px;
border: 1px solid red;
}
</style>
</head>
<body>
<form>
<!-- wrapper -->
<div class="wrapper">
<!-- canHdr -->
<div id="canHdr" class="canHdr" >
<p>
This is my 1st div with bezier curve the curve is getting drawn as slider moves and also a ball in moving on that .
</p>
<div class="canOuterHdr" >
<canvas id="myCanvas1" width="300" height="195" style="position: relative;">
[No canvas support]
</canvas>
</div>
<div id="slider1" class="newBg">
<input id="slide1" type="range" min="0" max="100" step="1" value="0" onchange="counterSlider('slide1');" />
</div>
</div>
<!--/ canHdr -->
<!-- canHdr2 -->
<div id="canHdr2" class="canHdr" >
<p>
This is my 2nd div
</p>
<div class="canOuterHdr" >
<canvas id="myCanvas2" width="300" height="195" style="position: relative;">
[No canvas support]
</canvas>
</div>
<div id="slider2" class="newBg">
<input id="slide2" type="range" min="0" max="100" step="1" value="0" onchange="counterSlider('slide2');" />
</div>
</div>
<!-- canHdr2 -->
<!-- canHdr3 -->
<div id="canHdr3" class="canHdr" >
<p>
This is my 3rd div with slanting line. I want to move a ball on this line when I move the slider. So as the line increases ball will also move on the line.
</p>
<div class="canOuterHdr" >
<canvas id="myCanvas3" width="300" height="195" style="position: relative;">
[No canvas support]
</canvas>
</div>
<div id="slider3" class="newBg">
<input id="slide3" type="range" min="0" max="100" step="1" value="0" onchange=" drawSlopeCurve2('slide3','100'); " />
</div>
</div>
<!--/ canHdr3 -->
<!-- canHdr4 -->
<div id="canHdr4" class="canHdr" >
<p>
This is my 4th div with slanting line. I want to move a ball on this line when I move the slider. So as the line increases ball will also move on the line.
</p>
<div class="canOuterHdr" >
<canvas id="myCanvas4" width="300" height="195" style="position: relative;">
[No canvas support]
</canvas>
</div>
<div id="slider4" class="newBg">
<input id="slide4" type="range" min="0" max="100" step="1" value="0" onchange=" drawSlopeCurve1('slide4','100'); " />
</div>
</div>
<!--/ canHdr4 -->
</div>
<!-- /wrapper -->
<script type="text/javascript">
function counterSlider(sID) {
var slideVal = document.getElementById(sID).value;
/*if (maxValue ==100){
slideVal=slideVal/100;
}*/
slideVal = slideVal / 100;
var position = slideVal;
var startPt = {
x : 18.8,
y : 45
};
var controlPt = {
x : 28,
y : 160
};
var endPt = {
x : 228,
y : 165
};
var startPt2 = {
x : 20,
y : 75
};
var controlPt2 = {
x : 28,
y : 160
};
var endPt2 = {
x : 228,
y : 165
};
if (slideVal == 0) {
erase('myCanvas2');
erase('myCanvas3');
erase('myCanvas4');
//newSprite('myCanvas1b', 18.8, 45);
drawBezier2('myCanvas1', new Array({
x : 18.8,
y : 45
}, {
x : 28,
y : 160
}, {
x : 228,
y : 165
}), slideVal);
drawBezier2('myCanvas2', new Array({
x : 20,
y : 75
}, {
x : 28,
y : 160
}, {
x : 228,
y : 165
}), slideVal);
} else if (slideVal > 0 && slideVal <= 34) {
erase('myCanvas1');
//erase('myCanvas1b');
erase('myCanvas2');
erase('myCanvas3');
erase('myCanvas4');
drawBezier2('myCanvas1', new Array({
x : 18.8,
y : 45
}, {
x : 28,
y : 160
}, {
x : 228,
y : 165
}), slideVal);
drawBezier2('myCanvas2', new Array({
x : 20,
y : 75
}, {
x : 28,
y : 160
}, {
x : 228,
y : 165
}), slideVal);
drawNextPoint('myCanvas1', startPt, controlPt, endPt, position);
drawNextPoint('myCanvas2', startPt2, controlPt2, endPt2, position);
} else if (slideVal > 34 && slideVal <= 67) {
erase('myCanvas1');
erase('myCanvas2');
erase('myCanvas3');
erase('myCanvas4');
drawBezier2('myCanvas1', new Array({
x : 18.8,
y : 45
}, {
x : 28,
y : 160
}, {
x : 228,
y : 165
}), slideVal);
drawBezier2('myCanvas2', new Array({
x : 20,
y : 75
}, {
x : 28,
y : 160
}, {
x : 228,
y : 165
}), slideVal);
drawNextPoint('myCanvas1', startPt, controlPt, endPt, position);
drawNextPoint('myCanvas2', startPt2, controlPt2, endPt2, position);
} else if (slideVal > 67 && slideVal <= 100) {
erase('myCanvas1');
erase('myCanvas2');
erase('myCanvas3');
erase('myCanvas4');
drawBezier2('myCanvas1', new Array({
x : 18.8,
y : 45
}, {
x : 28,
y : 160
}, {
x : 228,
y : 165
}), slideVal);
drawBezier2('myCanvas2', new Array({
x : 20,
y : 75
}, {
x : 28,
y : 160
}, {
x : 228,
y : 165
}), slideVal);
drawNextPoint('myCanvas1', startPt, controlPt, endPt, position);
drawNextPoint('myCanvas2', startPt2, controlPt2, endPt2, position);
}
}
function erase(canvasId) {
var canvas = document.getElementById(canvasId);
var context = canvas.getContext("2d");
context.beginPath();
context.clearRect(0, 0, canvas.width, canvas.height);
canvas.width = canvas.width;
}
/**********for backgroundImage********************/
function _getQBezierValue(t, p1, p2, p3) {
var iT = 1 - t;
return iT * iT * p1 + 2 * iT * t * p2 + t * t * p3;
}
function getQuadraticCurvePoint(startX, startY, cpX, cpY, endX, endY, position) {
return {
x : _getQBezierValue(position, startX, cpX, endX),
y : _getQBezierValue(position, startY, cpY, endY)
};
}
function drawNextPoint(canId, startPt, controlPt, endPt, position) {
var pt = getQuadraticCurvePoint(startPt.x, startPt.y, controlPt.x, controlPt.y, endPt.x, endPt.y, position);
position = (position + 0.006) % 1.0;
var canvas = document.getElementById(canId);
var ctx = canvas.getContext('2d');
//ctx.globalCompositeOperation = 'source-atop';
//ctx.globalCompositeOperation = "destination-over";
ctx.beginPath();
ctx.fillStyle = "#0077c1";
ctx.arc(pt.x, pt.y, 6, 0, Math.PI * 2, true);
ctx.closePath();
ctx.fill();
}
function newSprite(canId, mvx, mvy) {
var canvas = document.getElementById(canId);
var ctx = canvas.getContext('2d');
ctx.globalCompositeOperation = 'source-atop';
//ctx.globalCompositeOperation = "destination-over";
ctx.beginPath();
ctx.fillStyle = "#0077c1";
ctx.arc(mvx, mvy, 6, 0, Math.PI * 2, true);
ctx.closePath();
ctx.fill();
}
function drawBezier2(canId, points, slideVal) {
var canvas = document.getElementById(canId);
var context = canvas.getContext("2d");
//context.globalCompositeOperation = 'source-atop';
//context.strokeStyle = "rgb(113, 113, 213)";
context.strokeStyle = "#000";
context.lineWidth = 0.6;
context.beginPath();
// Label end points
//context.fillStyle = "rgb(0, 0, 0)";
// Draw spline segemnts
context.moveTo(points[0].x, points[0].y);
for (var t = 0; t <= slideVal; t += 0.1) {
context.lineTo(Math.pow(1 - t, 2) * points[0].x + 2 * (1 - t) * t * points[1].x + Math.pow(t, 2) * points[2].x, Math.pow(1 - t, 2) * points[0].y + 2 * (1 - t) * t * points[1].y + Math.pow(t, 2) * points[2].y);
}
// Stroke path
context.stroke();
}
function drawSlopeCurve1(sID, maxValue) {
// erase('canvasTwo');
var canId = 'myCanvas4';
var slideVal = parseInt(document.getElementById(sID).value);
var canvas = document.getElementById(canId);
var context = canvas.getContext('2d');
canvas.width = canvas.width;
//line end points
x1 = 16;
y1 = 170;
x2 = 200;
y2 = 80;
//get slope (rise over run)
var m = (y2 - y1) / (x2 - x1);
//get y-intercept
var b = y1 - (m * x1);
//get distance between the two points
var distance = Math.sqrt((x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1));
//get new x and y values
var x = x1 + parseInt(distance / maxValue * slideVal);
var y = parseInt(m * x + b);
context.beginPath();
context.moveTo(x1, y1);
context.lineTo(x, y);
context.lineWidth = 0.6;
context.stroke();
}
function drawSlopeCurve2(sID, maxValue) {
// erase('canvasTwo');
var canId = 'myCanvas3';
var slideVal = parseInt(document.getElementById(sID).value);
var canvas = document.getElementById(canId);
var context = canvas.getContext('2d');
canvas.width = canvas.width;
//line end points
x1 = 16;
y1 = 170;
x2 = 160;
y2 = 72;
//get slope (rise over run)
var m = (y2 - y1) / (x2 - x1);
//get y-intercept
var b = y1 - (m * x1);
//get distance between the two points
var distance = Math.sqrt((x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1));
//get new x and y values
var x = x1 + parseInt(distance / maxValue * slideVal);
var y = parseInt(m * x + b);
context.beginPath();
context.moveTo(x1, y1);
context.lineTo(x, y);
context.lineWidth = 0.6;
context.stroke();
}
</script>
</form>
</body>
</html>
Thanks in Advance. my jsfiddle link: http://jsfiddle.net/g7hWD/1/
You need to add the drawing code at the very end of functions drawSlopeCurve1() and drawSlopeCurve2(). The simplest way is to fix function newSprite() first and then use it (to avoid copying identical code-blocks over and over).
In function newSprite():
// Change that:
ctx.globalCompositeOperation = 'source-atop';
// To this:
ctx.globalCompositeOperation = "source-over";
(For more details on globalCompositeOperation see here.)
At the end of functions drawSlopeCurve1/2():
// Append this:
newSprite(canId, x, y);
See, also, this modified demo.

Categories