Nested for loops won't evaluate - javascript

I'm making an javascript image converter, just a proof of concept(I know there are another better languages for doing it). My problem is that in the loop section I'm doing some variables don't evaluate to the ones that are in the function loops. The code should work this way:
The HTML button activates the parent function.
Some variables are stated.
The loop that should make a nice gradient all over the and those I'm having trouble with are defined.
A function that triggers the loops in intervals is stated, with some other counter variables.e
I think the problem is in the counter variables I use on the loop() but I can't figure them out.
Here is all my code:
<!DOCTYPE html>
<html>
<head>
<html xmlns="http://www.w3.org/1999/xhtml">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>CPBitmap to PNG</title>
<style>
#canvas {
width:512px;
height:384px;
background-color:black;
}
</style>
<script>
function convertir(){
var y =0;
vertC = 10;
var pixelConverter = function(){
for(;y<vertC;y++){
for(var x=0; x<2048;x++){
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var pixel = "rgb(" + y + "," + vertC + "," + x + ")";
ctx.fillStyle = pixel;
ctx.fillRect(x,y,100,100);
}
}
}
intervalos = setInterval(loops,1);
function loops(){
pixelConverter();
vertC = vertC + 10;
console.log("Y= " + y + "Linea " + vertC );
y = y + 10;
x = 0;
console.log(x);
if(x > 2047 && y > 1535)intervalos=window.clearInterval(intervalos);
else pixelConverter();
}
}
</script>
</head>
<body>
<input type="file" id="input" name="file" />
<button onclick=convertir() >¡Convertir!</button>
<button onclick="intervalos=window.clearInterval(intervalos)">Alto</button>
<canvas id="canvas" width="2048px" height="1536px"></canvas>
<div id="Hola"></div>
</body>
</html>

Related

Variable not being defined

So I'm trying to get the variables x and y in the following code to determine the position of the image with the class myElement. On click it should set the top and left style to whatever the variables are (position of the cursor). When I test it out it just defaults to undefined.
<!doctype html>
<html>
<body onclick="getCoord(event)" style="height:2000px;">
<h2>click</h2>
<p id="display"></p>
<script>
function getCoord(event) {
var x = event.clientX;
var y = event.clientY;
var coord = "x:" + x + "y:" + y;
document.getElementById("display").innerHTML = coord;
console.log(x);
console.log(y);
document.getElementById('myElement').style.position = "absolute";
document.getElementById('myElement').style.top = y; //or whatever
document.getElementById('myElement').style.left = x; // or whatever]
};
</script>
<img id="myElement" src="https://picturethismaths.files.wordpress.com/2016/03/fig6bigforblog.png?w=419&h=364">
</body>
</html>
CSS Measurement
You had forgotten to add the measurement the numbers are to be interpreted as.
<!DOCTYPE html>
<html>
<body onclick="getCoord(event)" style="height:2000px;">
<h2>click</h2>
<p id="display"></p>
<script>
function getCoord(event) {
var x = event.clientX;
var y = event.clientY;
var coord = "x:" + x + " y:" + y;
document.getElementById("display").innerHTML = coord;
console.log(x);
console.log(y);
var myEle = document.getElementById('myElement'); // no need to use 3 times
myEle.style.position = "absolute";
myEle.style.top = y + "px"; // plus "px"
myEle.style.left = x + "px"; // plus "px"
};
</script>
<img id="myElement" src="https://picturethismaths.files.wordpress.com/2016/03/fig6bigforblog.png?w=419&h=364">
</body>
</html>

How do I separate two svgs using raphaël?

I'm a beginner beginner. I can get the behavior that I want to occur, but instead of occurring in two separate SVGs, all the behavior is occurring in 'svg2' although I have selected the respective ids for 'svg1' and 'svg2' (or at least I think I did)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<script src="https://code.jquery.com/jquery-3.0.0.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/raphael/2.2.0/raphael-min.js"></script>
<script src="logic.js"></script>
<title>Forms and Concentric Circles</title>
</head>
<body>
<h1>Forms and Concentric Circles</h1>
<div id="svg1"></div>
<div class="form">Add how many?
<input type="text" id="howmany" />
<button id="more">Add More</button></div>
<div id="svg2"></div>
<div class="form">
<button id="another">Add Another</button>
</div>
</body>
</html>
var paper;
disappear = function() {
this.remove();
}
spin = function(r) {
angle = Math.random()*1440 - 720;
initial = { 'transform': 'r0' }
final = { 'transform': 'r' + angle}
r.attr(initial);
r.animate(final, 2000);
}
addMore = function() {
rectNum = $('#howmany').val();
for (step = 0; step < rectNum; step += 1) {
x = Math.random() * 180;
y = Math.random() * 180;
r = paper.rect(x, y, 20, 20);
filled = {
'fill': '#ddf'
}
r.attr(filled);
r.click(disappear);
spin(r);
}
}
radius = 10
morecircles = function() {
paper.circle(100, 100, radius);
radius = radius + 10;
}
setup = function() {
paper = Raphael('svg1', 200, 200);
$('#more').click(addMore);
paper = Raphael('svg2', 200, 200);
$('#another').click(morecircles);
}
$(document).ready(setup);
change the name for the second svg for example
paper2.circle
and in your setup function it should be
paper2.Raphael('svg2',200,200)

Button not calling function correctly

I am trying to call a function on a button click, but for some reason the button will not call the function. Dreamweaver does not show any syntax errors. Can anyone tell me why the button is not working?
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
</head>
<head>
<title></title>
<script type="text/javascript">
var imgObj = 0;
var imgObj1 = 0;
var animate;
var animate1;
function init(){
imgObj = document.getElementById('red');
imgObj.style.position= 'relative';
imgObj.style.left = '0px';
imgObj1 = document.getElementById('blue');
imgObj1.style.position = 'relative';
imgObj1.style.left = '0px';
}
function moveRight(){
imgObj.style.left = parseInt(imgObj.style.left = 0) + Math.floor((Math.random() * 100) + 1) + 'px';
animate = setTimeout(moveRight(), 1000);
imgObj1.style.left = parseInt(imgObj1.style.left = 0) + Math.floor((Math.random() * 100) + 1) + 'px';
animate1 = setTimeout(moveRight(), 1000);
if (imgObj.style.left >= 1000px || imgObj1.style.left >= 1000px)
{
break;
else if
{
imgObj.style.left>= 1000
MessageBox.show("The Red Car has won the Race!");
}
else
{
MessageBox.show("The Blue Car has won the Race!");
}
}
}
</script>
</head>
<body onload = "init()">
<form>
<input type="button" value="Start" onclick="moveRight()" />
<br/><br/><br/><br><br/><br/><br/>
<img id="red" src="redcar.png" alt="Car 1"/>
<br/><br/><br/><br>
<img id="blue" src="bluecar.png" alt ="Car 2" />
</form>
</body>
</html>
Unfortunately there are so many errors that it's difficult to know where to start. The first answer to your question is that the button did nothing because your code doesn't compile. I don't know why Dreamweaver didn't report an error. Chrome's developer tools was more than happy to do so.
Here's a "working" version:
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title></title>
<script type="text/javascript">
var imgObj = 0;
var imgObj1 = 0;
var animate1;
function init(){
imgObj = document.getElementById('red');
imgObj.style.position= 'relative';
imgObj.style.left = '0px';
imgObj1 = document.getElementById('blue');
imgObj1.style.position = 'relative';
imgObj1.style.left = '0px';
}
function moveRight(){
var redPosition = parseInt(imgObj.style.left);
imgObj.style.left = redPosition + Math.floor((Math.random() * 20) + 1) + 'px';
var bluePosition = parseInt(imgObj.style.left);
imgObj1.style.left = bluePosition + Math.floor((Math.random() * 20) + 1) + 'px';
if (redPosition >= 1000 || bluePosition >= 1000)
{
if (redPosition >= 1000) {
alert("The Red Car has won the Race!");
}
else
{
alert("The Blue Car has won the Race!");
}
return;
}
animate1 = setTimeout(moveRight, 50);
}
</script>
</head>
<body onload = "init()">
<form>
<input type="button" value="Start" onclick="moveRight()" />
<br/><br/><br/><br><br/><br/><br/>
<img id="red" src="redcar.png" alt="Car 1"/>
<br/><br/><br/><br>
<img id="blue" src="bluecar.png" alt ="Car 2" />
</form>
</body>
</html>

javascript mouse coordinates with canvas and css

well right now im trying to learn how to use the canvas tag on html, and im having trouble handling mouse events when i apply css to the document.
the issue starts when i move the div containing the canvas and center it on the page, the first poing of the canvas wouldnt be 0 because its centered and for some reason 0,0 would be the beginning of the screen and not the beginning of the canvas, which i found weird because im adding the event listener to the canvas directly.
here is the code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>test</title>
<style type="text/css">
body {
font: 100%/1.4 Verdana, Arial, Helvetica, sans-serif;
background: #42413C;
margin: 0;
padding: 0;
color: #000;
}
#divId {
width: 800px;
height: 600px;
text-align:center;
margin: 20px auto;
background-color:#0099FF;
}
</style>
<script>
window.onload = function () {
var canvas = document.getElementById('canvasId');
var c = canvas.getContext('2d');
alert("lol");
canvas.addEventListener('mousedown', hmd, false);
function hmd(e) {
alert ("x: " + e.clientX + " y: " + e.clientY);
}
}
</script>
</head>
<body>
<div id="divId">
<canvas height="300" width="800" id="canvasId" />
</div>
</body>
</html>
so i read somewhere that the issue was caused by the div, but when i tried to give css directly to the canvas tag it didnt work, so basically what i need to do, is to get that canvas centered or placed anywhere on the screen, but having its first pixel as 0,0.
adding a solution would be hard because its centering automatically, so i would need to know the user resolution to be able to calculate the offset so what im looking for is a way to do it simply with css or something.
To get the coordinates relatively to the canvas, do this:
function hmd(e) {
var rx = e.pageX, ry = e.pageY;
rx -= canvas.offsetLeft;
ry -= canvas.offsetTop;
alert ("x: " + rx + " y: " + ry);
}
This assumes your canvas variable definition is global.
Edit: another method:
function hmd(e) {
var rx, ry;
if(e.offsetX) {
rx = e.offsetX;
ry = e.offsetY;
}
else if(e.layerX) {
rx = e.layerX;
ry = e.layerY;
}
}
Here's what I've been using for my latest experimentation. It works with damn near everything: Borders, paddings, position:fixed elements offsetting the HTML element, etc. It also works on all touch devices and even if the browser is zoomed.
http://jsfiddle.net/simonsarris/te8GQ/5/
var stylePaddingLeft = parseInt(document.defaultView.getComputedStyle(can, undefined)['paddingLeft'], 10) || 0;
var stylePaddingTop = parseInt(document.defaultView.getComputedStyle(can, undefined)['paddingTop'], 10) || 0;
var styleBorderLeft = parseInt(document.defaultView.getComputedStyle(can, undefined)['borderLeftWidth'], 10) || 0;
var styleBorderTop = parseInt(document.defaultView.getComputedStyle(can, undefined)['borderTopWidth'], 10) || 0;
var html = document.body.parentNode;
var htmlTop = html.offsetTop;
var htmlLeft = html.offsetLeft;
function getMouse(e) {
var element = can,
offsetX = 0,
offsetY = 0,
mx, my;
// Compute the total offset
if (element.offsetParent !== undefined) {
do {
offsetX += element.offsetLeft;
offsetY += element.offsetTop;
} while ((element = element.offsetParent));
}
// Add padding and border style widths to offset
// Also add the <html> offsets in case there's a position:fixed bar
offsetX += stylePaddingLeft + styleBorderLeft + htmlLeft;
offsetY += stylePaddingTop + styleBorderTop + htmlTop;
mx = e.pageX - offsetX;
my = e.pageY - offsetY;
// We return a simple javascript object (a hash) with x and y defined
return {
x: mx,
y: my
};
}

Why doesn't incPixel work as expected?

<!DOCTYPE html>
<html>
<head>
<meta lang="EN" />
<script type="text/javascript" src="jquery-1.4.4.min.js"></script>
<script type="text/javascript">
// Don't resize the window
function _(str){
return document.getElementById(str);
}
function incPixel(imageData, x, y){
var index = (x + y * imageData.width) * 4;
imageData.data[index + 0] = 155;
imageData.data[index + 1] = 155;
imageData.data[index + 2] = 155;
imageData.data[index + 3] = 155;
}
$(document).ready(function(){
// collect mouse position data
var history = [];
$(document).mousemove(function(e){
history.push([e.pageX, e.pageY]);
});
// when the button is clicked
$("#button").click(function(){
// 1. disable mouse position data collection
$(document).unbind("mousemove");
// 2. draw pixels on the canvas
var width = $(document).width();
var height = $(document).height();
$("#canvas").height(height).width(width);
var canvas = document.getElementById("canvas");
if(canvas.getContext){
var context = canvas.getContext("2d");
var imageData = context.createImageData(width, height);
for(var i=0; i<history.length; i++){
incPixel(imageData, history[i][0], history[i][1]);
}
context.putImageData(imageData, 0, 0);
alert(JSON.stringify(history));
}else{
alert("no context");
}
});
});
</script>
</head>
<body>
<h1>Hello, Worlds!</h1>
<div id="width"></div>
<div id="height"></div>
<input type="button" id="button" value="Click me" /><br />
<canvas id="canvas" />
</body>
</html>
You're missing the context type parameter from getContext(), it should be:
var context = canvas.getContext('2d');
You can test out a demo here with only the change above.

Categories