Shape rollover in JavaScript - javascript

I have drawn 2 images in canvas using javascript (lineTo, moveTo, rect etc.), and I want to manipulate these images in a rollover kinda way. I know I'm supposed to write functions like "onmouseover" and "onmouseaway", thing is I don't know how I can manipulate the two shapes I already have in the canvas given that I don't have their sources... I tried googling but it got a bit confusing.
alert: i'm beginner in JS
http://jsfiddle.net/aertop9416/J7Brj/embedded/result/
.js file
var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');
function drawTriangle(){
context.beginPath();
context.moveTo(225,275);
context.lineTo(25,25);
context.lineTo(0,275);
context.fill();
// context.fillStyle = 'rgb(200, 95, 124)';
};
function drawRect(){
context.fillRect(300,25,100,100);
// context.clearRect(245,245,60,60);
// context.strokeRect(250,250,50,50);
context.fillStyle = 'rgb(120, 195, 124)';
};

If you're not using a library such as EasleJS for interactivity (http://www.ajohnstone.com/test/hackday/CreateJS-EaselJS-b262a85/tutorials/Mouse%20Interaction/), It's going to be a bit tricky, since canvas uses immediate render mode you need to retain the state of your objects. Use the mouse interaction event listeners to trigger an animation loop (hopefully using requestAnimationFrame for performance see: http://www.paulirish.com/2011/requestanimationframe-for-smart-animating/). I hope this gets you going in the right direction.

Related

createjs removed all existing info on canvas?

I am trying to verify that this happens no matter what, and there's no way to bypass it. It seems pretty silly to me that createjs uses this architecture. But I noticed that creating a stage from an existing canvas element removes all shapes, writings, etc from the canvas? Code is below:
html:
<canvas id="canvas" width="800" height="400"></canvas>
js:
var canv = document.getElementById("canvas");
var stage = new createjs.Stage(canv);
var ctx = canv.getContext('2d');
ctx.beginPath();
ctx.arc(50,50,10,0,2*Math.PI);
ctx.stroke();
createjs.Ticker.addEventListener("tick", tick);//circle created is overwritten here!!!?! Why createjs!?
//stage.update();
createjs.MotionGuidePlugin.install();
var shape1 = new createjs.Shape();
shape1.graphics.f("#000000").dc(0,0,10);
var path1 = new createjs.Shape();
path1.graphics.beginStroke("#ff0000").mt(0,0).qt(50,100,100,0);
stage.addChild(path1, shape1);
createjs.Tween.get(shape1).to({guide:{ path:[0,0, 50,100, 100,0] }},2000, createjs.Ease.cubicInOut);
function tick(event) {
stage.update();
}
Is this something that cannot be bypassed? It seems silly to me that createjs wouldn't just actually use the existing element unerased. If not, what is the point in passing in an element in the first place, why doesn't it just create a canvas element, and give you the ID? Anyways, if this is how it's going to be, unfortunately, I am going to have to go somewhere else. Sad, because createjs seemed pretty useful.
CreateJS uses a retained graphics mode, that is, it stores the state and redraws it each time. This is because the canvas is basically a big Bitmap with drawing commands – clearing the stage is the only way to remove the previous state.
But good news! There are lots of ways to get around these limitations if you want to blend CreateJS content with other content, or even make additive drawing effects.
The first is easy, which is setting autoClear. This will prevent the clear, and just draw the new contents over the old one.
stage.autoClear = false;
The second is a bit tougher, but great for instances where you want to mix CreateJS content with other libraries or effects. You can basically use the other canvas as the source to a Bitmap you include in CreateJS:
// Create a child for CreateJS referencing the other canvas
var bmp = new createjs.Bitmap(otherCanvas);
// Add it at the bottom (or top or wherever) in your new CreateJS canvas
stage.addChildAt(bmp, 0);
This is a great approach because it lets you put your content wherever you want, edit it separately, etc.
If you have a different case this doesn't cover, let me know and I can try to make a recommendation!
Cheers.

Canvas - lines drawn but not showing up in google inspect element

I'm new to using canvas and am having a weird issue. My canvas lines are successfully being drawn using:
var canvas = document.getElementById('canvas'),
context = canvas.getContext('2d');
where canvas is the id of a canvas. I then draw using the methods:
context.strokeStyle = "red";
context.beingPath();
context.moveTo(x, y);
context.lineTo(x, y);
context.stroke();
with lineTo being called in a loop updating its position. I use these methods in a function and can draw multiple lines. The issue is (is it an issue?) when I use google's inspect elements I can't find these lines under the canvas that was created. I am used to seeing a path element of some sort.
I can see the script that created these lines, however.
EDIT: just checked another website using canvas and this seems to be normal behavior. Would like confirmation though.
Thanks
Yes It's normal behaviour.
In 2012 the chrome have some experimental plugin with help inspect canvas. But I not sure if it still avaiable (I found information here http://www.html5rocks.com/en/tutorials/canvas/inspection/)

Tweenjs Blurring inside Container

I've been stuck on this for about a week now and can't figure out why the shape instance inside my container is getting blurred when it is animated at 60 fps. My container holds one shape instance. The shape instance is associated with one graphics instance. There seems to be a white blur that trails the direction of the animation. Is there a way to stop this blurring or is it a limitation of tweenJS? Here's the jsFiddle.
http://jsfiddle.net/1chh2de6/
Here are some additional details, I am working on a billiards game which involves a lot of moving circles. I've created a class for each pool ball, which will hold more shape instances in the future. However, at 60 fps the shape instances are blurred during animations. Here's the 'poolBall' class.
function poolBall(number, posX, posY) {
this.number = number;
this.shapesArray = [];
this.shapesArray.push(new createjs.Shape());
this.containerInstance = new createjs.Container();
this.containerInstance.addChild(this.shapesArray[0]);
this.containerInstance.x = posX;
this.containerInstance.y = posY;
this.drawGraphic = function(){
this.shapesArray[0].graphics.beginFill('white')
.setStrokeStyle(1)
.beginStroke("#000000")
.drawCircle(14, 14, 14)
.endFill()
.endStroke();
};
};
This is just a symptom of how the canvas displays the contents as they change, and not related to EaselJS or TweenJS. Here is a fiddle using raw canvas APIs.
http://jsfiddle.net/lannymcnie/97vLu9q9/1/
Circle Code
context.beginPath();
context.arc(0,0,20,0,2* Math.PI,false);
context.fillStyle = "white";
context.fill();
context.lineWidth = 1;
context.strokeStyle = "black";
context.stroke();
Note that I used RequestAnimationFrame to update the stage. I tested RAF with EaselJS as well, with no change in how it animated.
Unless I'm missing something here, this is just persistence of vision, which is just how normal human vision works, especially with high contrast graphics on computer screens.
Try going outside on a dark night and waving a bright light back and forth, you will similarly see a subtle "trail" behind it.
An even better way to prove this, is to capture a screen shot while the animation is happening. Looking at the static frame, you will see that it does not have the blur.

Visualizing html5 canvas

This may be off topic but I'm not sure where else to go with this question. I'm just getting started with HTML5 canvas element and all of the incredibly powerful things it can do. I was hoping someone could offer some advise. When working with custom paths and bezier curves, what is the easiest/best way to visualize where the points belong on the canvas to achieve a desired effect. Right now it feels like I'm just guessing plotting points in any place hoping to end up with the right angle/shape that I want.
To be more specific I want to create a shape that will act as an image mask, and will later need to animate this shape. Much like this fiddle http://jsfiddle.net/jimrhoskins/dDUC3/1/ (someone else's work) but since I can't see where the picture is on the canvas or where any of the points are, I'm really just guessing at the approximate shape I need to make. I'm just wondering if there's a better way, or some function in javascript that can map the location of an image and give me at least a better place to start.
Here is what I know/have tried already
// Grab the Canvas and Drawing Context
var canvas = document.getElementById('c');
var context = canvas.getContext('2d');
// Create an image element
var img = document.createElement('IMG');
// When the image is loaded, draw it
img.onload = function () {
// Save the state, so we can undo the clipping
context.save();
// Create a shape, of some sort
context.beginPath();
context.moveTo(somex, somey);
context.bezierCurveTo(somexstart, someystart, somexcontrol, someycontro, somexend, someyend);
context.arcTo(somecoordinates);
context.closePath();
// Clip to the current path
context.clip();
context.drawImage(img, 0, 0);
// Undo the clipping
context.restore();
}
// Specify the src to load the image
img.src = "url";
How about opening the image in an SVG editor. Drawing a path on a layer above the image. Then open the SVG and copy the coordinates?
Try an SVG Editor. You can get the points there. You can add images too. SVG animation is used nowadays as well. If you have Adobe Illustrator, it will be easier to draw there and just save it as SVG.

Problems clearing canvas when animating a clipping region

I'm trying to accomplish an effect similar to what you might see on the cartoon Chowder (example link) , where shapes serve as masking layers for a texture underneath that stays static. I've begun playing around with this idea by creating a render loop that clears the canvas, saves it's state, then draws a rectangular clipping region, followed by drawing the background texture that occupies the entire width and height of the canvas.
Here's the draw function:
function draw()
{
context.clearRect(0,0, 640, 480);
context.save();
x += velocityX;
y += velocityY;
context.rect(x, y, 40, 40);
context.clip();
context.drawImage(image, 0,0, 640, 480);
context.restore();
}
Basically it just runs at 60 frames per second, updating the position of the rectangle and clipping a background image inside the clipping region. (I know the code isn't structured perfectly, but I was just experimenting to see if this effect was even possible on the canvas).
http://jsfiddle.net/JERje/86/
The problem I seem to be having is that the clipping area from the previous iteration of the loop hangs around creating the weird effect that you see in the fiddle above. I've tried reordering everything in the draw() step of the loop, but the only thing that seems to work is the canvas.width = canvas.width trick for clearing the screen. I'd like to avoid this method of clearing the screen, since it doesn't seem to work in IE, and it also destroys the canvas state. clearRect() should work to clear the screen. What am I doing wrong?
You're using the same HTML5 Canvas paperback I am aren't you.
If you set up an adhoc canvas as I did on your jsfiddle like so:
var newCanvas = document.createElement('canvas');
newCanvas.getContext("2d").drawImage(image,0,0);
A function such as this would be able to hack a section out of that canvas:
context.putImageData(newCanvas.getContext("2d").getImageData(x,y,40,40),x,y);
Thus giving you the chowder effect. Good show man, good luck. Pst me if it doesn't work
EDIT: However this solution will ignore some context scaling transformations. Just be smart about how you handle scale on your own (and you really should be anyways if you want the true "chowder" effect)
So, feel pretty dumb about this, but apparently when you call rect() you also have to make sure to call closePath afterwards in order to close the clipping area. Glad I figured it out finally, now on to adding multiple layers!
Here's the working fiddle: http://jsfiddle.net/JERje/129/

Categories