Making simple paint in html 5 canvas - html

I have simple code to "draw" in canvas element:
function doFirst(){
var x = document.getElementById('canvas');
canvas = x.getContext('2d');
window.addEventListener("mousemove", rys, false);
}
function rys(e){
var xPos = e.clientX;
var yPos = e.clientY;
canvas.fillStyle="#000";
canvas.beginPath();
canvas.arc(xPos-7,yPos-7,10,0,Math.PI*2,true);
canvas.closePath();
canvas.fill();
}
window.addEventListener("load", doFirst, false);
As you can see, the function is working only when the mouse is over the canvas element. Now i want to make it "draw" when the mouse is clicked (just like in paint). Can someone tell me how to do it (with code)?
Thx for help

You need to keep track of the current mouse button state (pressed or not pressed) independently of the mouse movements.
You can do this by attaching event handlers to the "mousedown" and "mouseup" events, similar to how you attached to the "mousemove" event.
In these event handlers, you could keep track of the current state of the first mouse button by updating a global variable indicating whether or not the button is currently pressed. Then, in your "mousemove" handler, you can check this global variable and determine whether or not to paint when the mouse is moved.
When using the "mouseup" and "mousedown" events, you may want to limit your handling to only when the first mouse button is pressed. You can do this by checking that the event property "button" is 0. Note, that you can check for other buttons and keep track of them, also.
You can see a working example of this here: http://jsfiddle.net/mQtKz/

Related

Actionscript: BlitMask stopping mouse event listeners from working, how to fix?

I have a button class which contains event listeners to trigger an animation of the button on click.
I used many instances of this class to form a list which the user can scroll through. I have implemented BlitMask, this works, however the mouse event listeners in the button class no longer work. This code
_blit = new BlitMask(_mc, _obounds.x, _bounds.y, _bounds.width, _bounds.height, false);
Is what stops the button class.
How can I get the behaviour pre blitmark?
My code which creates the bottom is
var tf:TextField = new TextField(text);
tf.x = 70;
tf.y = 20;
_btn.addChild(tf);
_btn.addEventListener(MouseEvent.CLICK, click);
click is never called.
The blitmask causes the movieclip to be nothing more than an image of clip.
bitmapMode must be set to false to correct this.
_blitMask.bitmapMode = false;
EDIT: To expand on a further issue that implementing this solution causes, turning bitmapMode on only when needed causes the bitmap to not reflect changes in the classes that changed while bitmapMode was off. So you must set
_blitMask.update(null, true);
To force a full update when you use
_blitMask.bitmapMode = true;

AS3 - how to get the mouse cursor to click on a button?

In my application i have a mouse cursor which is attached to the mouse. However it will not let me click on buttons within my application which is a big problem for me as buttons are essential in what i need to do.
I am new to AS so any help would be much appreciated!
stage.addEventListener(MouseEvent.MOUSE_MOVE, draw_cursor);
stage.addEventListener(Event.MOUSE_LEAVE, hide_cursor);
Mouse.hide();
function draw_cursor(event:MouseEvent):void
{
my_cursor_mc.visible = true;
my_cursor_mc.x = event.stageX;
my_cursor_mc.y = event.stageY;
}
function hide_cursor(event:Event):void
{
my_cursor_mc.visible=false;
}
i tried using this (below) but was very glichy and had to press button for cursor to go away THEN i was able to click on the button (not really ideal):
stage.addEventListener(MouseEvent.CLICK, hide_cursor);
Sounds like your cursor might be stealing the mouse events for your buttons. In your top level code (or constructor) try adding:
// Disable mouse events for cursor
my_cursor_mc.mouseEnabled = false;
If you mouse event has any child objects also add:
// Disable mouse events for any children of the cursor
my_cursor_mc.mouseChildren = false;

Repeating Button - If you keep it depressed, it keeps firing a function

I am not sure what to call this, all I can think of is a Repeater Button.
I want to press a button and it fires a function immediately once, eg MyZoom(InOrOut).
But if I keep the mouse button depressed it will keep firing that MyZoom(InOrOut) every one tenth of a second until I release the mouse button.
As you can probably guess from the function name, I will have 2 buttons, a zoom in and a zoom out. They will call MyZoom(-1) to make it smaller and MyZoom(1) to make it bigger.
<button onclick="MyZoom(-1);">Zoom Out</button>
<button onclick="MyZoom(1);">Zoom In</button>
How can I change this to include the repeating effect?
Use the onmousedown and onmouseup events.
In onmousedown start an interval and stop it in onmouseup.
Here's a small example using jQuery:
HTML:
<button class="zoomButton" data-zoom="out">Zoom Out</button>
<button class="zoomButton" data-zoom="in">Zoom In</button>
JavaScript:
var zoomIntervals = {};
$('.zoomButton').on('mousedown', function() {
var mode = $(this).data('zoom');
zoomIntervals[mode] = setInterval(function() {
// here you perform your action.
// check if mode == 'in' or mode == 'out' to determine if
// the user is zooming in or out
}, 100);
}).on('mouseup', function() {
var mode = $(this).data('zoom');
clearInterval(zoomIntervals[mode]);
del zoomIntervals[mode];
});
If you do not (want to) use jQuery, use addEventListener() to register the events and either access the data properties directly (not compatible with older browsers) or use e.g. the ID property to identify the buttons.
I would use jQuery for this. There is an event called mousedown and another event called mouseup that would help you to do that. Basically mousedown event starts a timer (repeating it) that gets stopped when mouseup event is fired.
You could have something like this:
$('#myzoominbutton').mousedown(function() {
alert('zooming is cool');
});

HTML5 Animation, capture mouse movement without interruption?

I have a slight problem here I try to solve. As I start to do animation with HTML5 and Canvas I want to have a constant animation flow and also be able to capture mouse movement without interrupting the animation flow. This right now seems like a problem. Ill bring
some code from my test code here.
function mainInit()
{
canvas = document.getElementById('canvas');
context = canvas.getContext('2d');
ballArray.push(new Ball(30,30,2,4,15,"#EEEEEE"));
setInterval(drawScene,20);
}
function drawScene()
{
// main drawScene function
clear(); // clear canvas
// draw animated objects
for(var i = 0; i < ballArray.length; i++)
{
ballArray[i].draw();
}
Event_MouseMove();
}
var messageMousePos = '';
function Event_MouseMove()
{
canvas.addEventListener('mousemove', function(evt)
{
var mousePos = getMousePos(canvas, evt);
messageMousePos = "Mouse position: " + mousePos.x + "," + mousePos.y;
context.font = '10pt Calibri';
context.fillStyle = 'black';
context.fillText(messageMousePos , 5, 15);
}, false);
}
The problem is that when I move the eventListner for mouse movement overrides the draw interval and makes it go much slower. How/where should I put the code for the mouse event so it do not interrupt this draw interval, but still draw the mouse events according to the interval?
At a glance, it looks like the code will try to add an event listener every frame...While JS will dump duplicate handlers, it will slow your code down. It's unclear whether you are trying to only capture mouse movement every interval, or constantly, because your code is kinda trying to do both. Here's the best of both worlds solution:
Call addEventListener once outside the loop, and have the function it calls save the mouse position in messageMousePos. Then, within the drawScene function, put your font/fillstyle/filltext code if you really do only want the text outputting every 20ms. This might look choppy compared to how smoothly the text would change if you were constantly rendering the mouse position text.
Here is an example of constantly capturing and displaying the mouse position, as you might actually want to do.

Difference between e.target and e.currentTarget

I don't understand the difference, they both seem the same but I guess they are not.
Any examples of when to use one or the other would be appreciated.
e.target is what triggers the event dispatcher to trigger and e.currentTarget is what you assigned your listener to.
Ben is completely correct in his answer - so keep what he says in mind. What I'm about to tell you isn't a full explanation, but it's a very easy way to remember how e.target, e.currentTarget work in relation to mouse events and the display list:
e.target = The thing under the mouse (as ben says... the thing that triggers the event).
e.currentTarget = The thing before the dot... (see below)
So if you have 10 buttons inside a clip with an instance name of "btns" and you do:
btns.addEventListener(MouseEvent.MOUSE_OVER, onOver);
// btns = the thing before the dot of an addEventListener call
function onOver(e:MouseEvent):void{
trace(e.target.name, e.currentTarget.name);
}
e.target will be one of the 10 buttons and e.currentTarget will always be the "btns" clip.
It's worth noting that if you changed the MouseEvent to a ROLL_OVER or set the property btns.mouseChildren to false, e.target and e.currentTarget will both always be "btns".
I like visual answers.
When you click #btn, two event handlers get called and they output what you see in the picture.
Demo here: https://jsfiddle.net/ujhe1key/
e.currentTarget is always the element the event is actually bound do. e.target is the element the event originated from, so e.target could be a child of e.currentTarget, or e.target could be === e.currentTarget, depending on how your markup is structured.
target is the element that triggered the event (e.g., the user clicked on)
currenttarget is the element that the event listener is attached to.
It's worth noting that event.target can be useful, for example, for using a single listener to trigger different actions. Let's say you have the typical "menu" sprite with 10 buttons inside, so instead of doing:
menu.button1.addEventListener(MouseEvent.CLICK, doAction1);
menu.button2.addEventListener(MouseEvent.CLICK, doAction2);
etc...
You can simply do:
menu.addEventListener(MouseEvent.CLICK, doAction);
And trigger a different action within doAction(event) depending on the event.target (using it's name property, etc...)
make an example:
var body = document.body,
btn = document.getElementById( 'id' );
body.addEventListener( 'click', function( event ) {
console.log( event.currentTarget === body );
console.log( event.target === btn );
}, false );
when you click 'btn', and 'true' and 'true' will be appeared!
e.currentTarget would always return the component onto which the event listener is added.
On the other hand, e.target can be the component itself or any direct child or grand child or grand-grand-child and so on who received the event. In other words, e.target returns the component which is on top in the Display List hierarchy and must be in the child hierarchy or the component itself.
One use can be when you have several Image in Canvas and you want to drag Images inside the component but Canvas. You can add a listener on Canvas and in that listener you can write the following code to make sure that Canvas wouldn't get dragged.
function dragImageOnly(e:MouseEvent):void
{
if(e.target==e.currentTarget)
{
return;
}
else
{
Image(e.target).startDrag();
}
}
e.target is element, which you f.e. click
e.currentTarget is element with added event listener.
If you click on child element of button, its better to use currentTarget to detect buttons attributes, in CH its sometimes problem to use e.target.
e.currentTarget is element(parent) where event is registered, e.target is node(children) where event is pointing to.