Grid Zoom - html5 canvas transformations not working - html

I'm very new to coding. My project is to zoom in to an canvas image based on a 100px square. My selector square is moving around the image successfully with the old squares deleted as I move around the grid.
Here's my code:
HTML
<!doctype HTML>
<html lang="en">
<head>
<script src="draw.js"></script>
</head>
<body>
<section id="main">
<canvas id="canvas" width="400" height="600" style='border:3px solid red'>
</canvas>
</section>
</body>
JAVASCRIPT
function doFirst(){
var x = document.getElementById('canvas')
canvas=x.getContext('2d');
canvas.strokeStyle = "blue";
var pic= new Image();
pic.src = "tut.jpg";
pic.addEventListener ("load",function(){canvas.drawImage(pic,0,0)},false);
}
function select(e){
var xPos=e.clientX;
var yPos=e.clientY;
var locationX = Math.floor(xPos/100)*100
var locationY = Math.floor(yPos/100)*100
var pic= new Image();
pic.src = "tut.jpg";
canvas.drawImage(pic,0,0);
canvas.strokeRect(locationX,locationY,100,100);
}
function zoom (e) {
var locationX = Math.floor(xPos/100)*100
var locationY = Math.floor(yPos/100)*100
canvas.translate(-locationX,-locationY);
canvas.scale(5,5);
}
window.addEventListener ("load", doFirst, false);
window.addEventListener ("mousemove", select, false);
window.addEventListener("mousedown",zoom,false);
The zoom function doesn't kick in at all. And I'm not sure how to move on from there next function - a simple colouring app -= rather than going back to the select function once it has - order functions is still a bit of a mystery. Excuse any naivety as I've probably made some huge clangers in this code.
All help much appreciated,
Nick

To answer your question regarding zoom():
Variables in JavaScript operate under function scope. That is, any variables declared in a function remain visible only to whatever's inside that function.
When you attempt to use xPos and yPos in zoom(), you will get undefined values for them because xPos and yPos are only declared inside select().
xPos and yPos need to be declared and calculated in zoom() as well.

Of course! Thank you.
The zoom function seems a little harder to perfect than I thought: The scale seems to throw the offset out.
Also my animated square refreshed differently on Chrome and IE. How strange. Smooth on IE but flashes on Chrome.
Is there a good place to read up about creating a sequence of function events or do I just put one function inside the other?
Really appreciate your help,
Nick

Related

Animate CC HTML5 easelJS stage.X stage.Y mouse position not consistent between chrome and and firefox

I have an application where I need an information card to follow the position of the mouse.
I have used the following code:
stage.addEventListener("tick", fl_CustomMouseCursor.bind(this));
function fl_CustomMouseCursor() {
this.NameTag.x = stage.mouseX;
this.NameTag.y = stage.mouseY;
}
It works perfectly in Firefox but in Chrome and Safari the further away the mouse gets from 0,0 on the canvas the larger the distance between NameTag and the mouse (by a factor of 2).
I look forward to any comments.
I see the issue in Chrome as well as Firefox - I don't believe it is a browser issue.
The problem is that the stage itself is being scaled. This means that the coordinates are multiplied by that value. You can get around it by using globalToLocal on the stage coordinates, which brings them into the coordinate space of the exportRoot (this in your function). I answered a similar question here, which was caused by Animate's responsive layout support.
Here is a modified function:
function fl_CustomMouseCursor() {
var p = this.globalToLocal(stage.mouseX, stage.mouseY);
this.NameTag.x = p.x;
this.NameTag.y = p.y;
}
You can also clean up the code using the "stagemousemove" event (which is fired only on mouse move events on the stage), and the on() method, which can do function binding for you (among other things):
stage.on("stagemousemove", function(event) {
var p = this.globalToLocal(stage.mouseX, stage.mouseY);
this.NameTag.x = p.x;
this.NameTag.y = p.y;
}, this);
Cheers,

html5 canvas drawImage not loading in Chrome

I am using the following code to wait for all images to load before drawing them onto the canvas. This works great in Firefox and works great when I enter the url of the page directly into the address bar of Chrome. However, when I attempt to use the refresh button in Chrome the images fail to load.
var need_to_load = 2;
var items = 0;
function item_loaded() {
items +=1;
if (items >= need_to_load) {
context.drawImage(router_pic,router_x,router_y,80,80);
context.drawImage(switch_pic,router_x,switch_y,60,60);
}
} // end item_loaded
var router_pic = new Image();
router_pic.src = "images/router.png";
router_pic.onload = item_loaded();
var switch_pic = new Image();
switch_pic.src = "images/switch.png";
switch_pic.onload = item_loaded();
Can someone point me in the right direction as to why and how to make this work with Chrome?
I realize in this case I can get rid of the item_loaded() function, but I have another more complicated canvas drawing where it makes the most sense to wait for all images to load before drawing them to the canvas.
Chrome version is 33.0.1750.152 if that makes any difference.
You're currently using the onload handler wrong. It need to have only a reference to the handlers - here the result of those functions are returned to it instead.
Simply change these lines:
router_pic.onload = item_loaded; //no parenthesis
switch_pic.onload = item_loaded;
I would also recommend switching the onload line with src line so src comes last.
Hope this helps!

Best way to programmatically manipulate an hand-drawn line

Please notice that I have no background on mathematics or computer graphics.
I would like to know the best way to programmaticaly manipulate an hand-drawn line, if it is even possible.
The draw action must be done in a html page. (may be irrelevant)
methods I tough off:
Draw a line into a canvas (hand-drawn line with up and downs) -> convert to bitmap -> somewhow intepret line on bitmap and manipulate its form (is this possible?)
Instead of interpret from bitmap, at the drawing moment have a kind of button to toggle capture on/off and after capture, generate some kind of mathematical function wich I am able to manipulate and from it generate the new bitmap
Yes, you can.
It's not difficult, but there are lots of small coding aspects to learn.
If you’re in “drawing” mode, you would collect mousepoints that the user clicks and make a line from all those points.
If you’re in “editing” mode, you would let the user drag one of those collected points to a new coordinate and make a line from all the edited points.
Here’s starting code for you to look and learn from plus a Fiddle: http://jsfiddle.net/m1erickson/J5PrN/
<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" media="all" href="css/reset.css" /> <!-- reset css -->
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<style>
body{ background-color: ivory; }
#canvas{border:1px solid red;}
</style>
<script>
$(function(){
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
ctx.lineCap = "round";
ctx.lineJoin = "round";
ctx.lineWidth=3;
var canvasOffset=$("#canvas").offset();
var offsetX=canvasOffset.left;
var offsetY=canvasOffset.top;
var isDown=false;
var startX;
var startY;
var points=[];
var selected=-1;
var mode="draw";
function draw(){
ctx.clearRect(0,0,canvas.width,canvas.height);
ctx.beginPath();
ctx.moveTo(points[0].x,points[0].y);
for(var i=1;i<points.length;i++){
ctx.lineTo(points[i].x,points[i].y);
}
ctx.stroke();
if(mode=="edit"){
for(var i=0;i<points.length;i++){
ctx.beginPath();
ctx.arc(points[i].x,points[i].y,10,0,Math.PI*2);
ctx.closePath();
ctx.fill();
}
}
}
function handleMouseDown(e){
startX=parseInt(e.clientX-offsetX);
startY=parseInt(e.clientY-offsetY);
if(mode=="draw"){
points.push({x:startX,y:startY});
draw();
}else if(mode=="edit"){
for(var i=0;i<points.length;i++){
var pt=points[i];
var dx=startX-pt.x;
var dy=startY-pt.y;
if(dx*dx+dy*dy<100){
selected=i;
return;
}
}
}
}
function handleMouseUp(e){
selected=-1;
}
function handleMouseOut(e){
selected=-1;
}
function handleMouseMove(e){
if(selected<0){return;}
mouseX=parseInt(e.clientX-offsetX);
mouseY=parseInt(e.clientY-offsetY);
// Put your mousemove stuff here
if(selected<0){return;}
var dx=mouseX-startX;
var dy=mouseY-startY;
startX=mouseX;
startY=mouseY;
var pt=points[selected];
points[selected]={x:pt.x+dx,y:pt.y+dy};
draw();
}
$("#canvas").mousedown(function(e){handleMouseDown(e);});
$("#canvas").mousemove(function(e){handleMouseMove(e);});
$("#canvas").mouseup(function(e){handleMouseUp(e);});
$("#canvas").mouseout(function(e){handleMouseOut(e);});
$("#draw").click(function(){
mode="draw";
draw();
$instructions.text("Click points to draw a line");
});
$("#edit").click(function(){
mode="edit";
draw();
$instructions.text("Drag points to move the line");
});
$instructions=$("#instructions");
}); // end $(function(){});
</script>
</head>
<body>
<button id="draw">Add to Line</button>
<button id="edit">Change Line</button><br>
<p id="instructions">Click points to draw a line</p>
<canvas id="canvas" width=300 height=300></canvas>
</body>
</html>
I can't speak to HTML, but in most applications I have seen (such as this one), hand drawn lines are broken up into small straight segments. This is because the sensing system (touch or mouse) gives your application a (somewhat) continuous stream of points; it does not give the actual line. The individual segments are then used to do whatever the goal of the application is.
In the case of line drawing, as the line is drawn, the application takes the points and smooths them (cubic spline, least squares polynomial fit, b-spline, etc.) then draws the smoothed lines onto the screen in the color and style (pen, pencil, chalk, etc.). This gives the user immediate feedback about where their hand is moving, etc.
In the case of gestural control, some overlay line may be drawn to give the user feedback, but the segments are processed differently to determine the gesture (this can be very complex).
Having the lines cached as a series of gestures gives you options for undo/redo. You can also store the drawing as a series of gestures instead of a fixed bitmap.
Was this helpful?

Drawing on HTML5 Canvas

Is there a putpixel functionality in html5. I have a canvas and want to draw on the canvas using mouse. How should I wright the javascript function for that. How can can I take the coordinate value on mouseclick and change the pixel value as soon as the user clicks.
From http://net.tutsplus.com/tutorials/javascript-ajax/canvas-from-scratch-pixel-manipulation/ section "Putting this into practice" using jquery:
$(canvas).click(function(e) {
var canvasOffset = $(canvas).offset();
var canvasX = Math.floor(e.pageX-canvasOffset.left);
var canvasY = Math.floor(e.pageY-canvasOffset.top);
// do here whatever you want
});
Read the article for a detailed explanation.
If you have a intermediate knowledge of Javascript try reading a tutorial like this:
http://www.williammalone.com/articles/create-html5-canvas-javascript-drawing-app/

HTML5 webpage animation

Does anybody know how to achieve something like that?
http://teamviget.com/#!lift-off
I want to do something similar but I'm something new in html5 and all this stuff
Thanks!
Of course you can do. First of all the you gotta draw the background image. And provide two buttons on either side. Onclick of these buttons you call a function... which inturn calls an setInterval() function that animates(here in your case the image has to fade and a new image has to be formed) . For providing fading effect we have a popular parameter. ctx.globalAlpha(). In each animation step change the value of it. Lemme provide a sample code so that you can understand it properly.
canvas = document.getElementById("canvas");
ctx = canvas.getContext("2d");
var ms = new Image();
ms.src = "images/asdf.jpg"
ctx.drawImage(ms,0,0); // Will draw the initial image (assume)
ctx1 = canvas.getContext("2d");
Now let me define the onclick function.
onclick="caller()";
The caller function should be made to call the animate function
function caller()
{
i=1;
inter=setInterval(animate(),500); // Calls the animate function every 500 msec
}
And the animate function would look as shown below
function animate()
{
i=i-0.1;
ctx1.globalAlpha=i;
if(i=0)
{
clearInterval(inter);
ctx1.drawImage(ms2,0,0); // This will draw the next image defined in ms2.
}
}
So the image will be faded out and a new image appears in 5 secs. Use an array if you have several images and definitely javascipts would help you to implement them all the way you want. Let me know if you need any more clarifications to a SPECIFIC problem that you are facing.