HTML5 Canvas Drawing - html

I have a 100 (width) x 100 (Height) canvas arranged in a row and column of 5 x 6
it has a triangle drawn on them currently the canvas are arranged in such a way that every canvas overlaps each other. i want to add click on the triangle area
is there a way to bypass click to the underlying canvas when the click is in transparent area of the top canvas

With EaselJS, you can use the nextStage property to pass CreateJS mouse interactions to canvases that are below one another in the DOM.
// Overlapping Canvases
<canvas id="canvas1"></canvas>
<canvas id="canvas2"></canvas>
// Multiple Stages
stage1 = new createjs.Stage("canvas1"),
stage2 = new createjs.Stage("canvas2");
// Mouse events on content in each stage
stage1child.on("click", handleClick);
stage2child.on("click", handleClick);
// Stage 2 is higher in the DOM, so it will receive the mouse events first.
// Pass them on to the lower canvas/stage
stage2.nextStage = stage1;
Here is more info:
nextStage documentation
TwoStages demo in GitHub
TwoStages demo on createjs.com

I didn't entirely understood your question, but if you just want for the click to register to the Canvas bellow the shape, then you need to disable the mouse interaction for the shape on top, like this:
triangleShape.mouseEnabled = false;
By doing so, any mouse events will be ignored for this shape and passed instead to the objects bellow it.

Related

Building an web based image annotation tool - saving annotations to localStorage

I am building a web application for annotating images. The work flow is as follows:
Select a project - using : action = list all sub-projects
Click on a sub-project : action = fetch all the images within-sub project
Display the images as a horizontal scrollable thumbnail gallery
Onclick image thumbnail from the gallery, display the larger image for annotation.
I am using canvas to display larger image. I have used another canvas as a layer to the first one, and I am able to draw rectangles using mouse over regions of interest. I am saving it locally. However, when I move on to the next image, the rectangle also gets carried to the next image.
My question is, instead of using just one layer, do I have to dynamically create as many canvas layers as I have in the annotation dataset. I am not sure because in each sub project I have around 8000-9000 images. Though I wont be annotating on all of them, still creating as many canvases as layers doesn't really sound good for me.
The following is the code:
HTML Canvas
<div class="body"> <!-- Canvas to display images begins -->
<canvas id="iriscanvas" width=700px height=700px style="position:absolute;margin:50px 0 0 0;z-index:1"></canvas>
<canvas id="regncanvas" onclick="draw(this, event)" width=700px height=700px style="position:absolute;margin:50px 0 0 0;z-index:2"></canvas>
</div> <!-- Canvas to display images ends -->
Step 4 given above: OnClick display thumbnail
function clickedImage(clicked_id) {
var clickedImg = document.getElementById(clicked_id).src;
var clickedImg = clickedImg.replace(/^.*[\\\/]/, '');
localStorage.setItem("clickedImg", clickedImg);
var canvas = document.getElementById("iriscanvas");
var ctx = canvas.getContext("2d");
var thumbNails = document.getElementById("loaded_img_panel");
var pic = new Image();
pic.onload = function() {
ctx.drawImage(pic, 0,0)
}
thumbNails.addEventListener('click', function(event) {
pic.src = event.target.src;
});
}
Draw rectangles on second layer of canvas
window.onload=function(){
c=document.getElementById("regncanvas");
if (c) initCanvas(c);
};
function initCanvas(canvas){
// Load last canvas
loadLastCanvas(canvas);
}
function draw(canvas, event){
// Draw at random place
ctx=c.getContext("2d");
ctx.fillStyle="#ff0000";
ctx.beginPath();
ctx.fillRect (250*Math.random()+1, 220*Math.random()+1, 40, 30);
ctx.closePath();
ctx.fill();
// Save canvas
saveCanvas(canvas);
}
function saveCanvas(c){
localStorage['lastImgURI']=c.toDataURL("image/png");
}
function loadLastCanvas(c){
if (!localStorage['lastImgURI']) return;
img = new Image();
img.onload = function() {
ctx=c.getContext("2d");
ctx.drawImage(img, 0, 0, img.width, img.height);
};
img.src= localStorage['lastImgURI'];
}
Can someone guide me please?
The following is a screen grab of my application:
I have developed OCLAVI which is an image annotation tool with loads of features. It's still in beta but just after 3 weeks of release, it is gaining attraction quickly.
I have few advises for you.
HTML Canvas follow draw and forget strategy and every time redrawing the image is not a good idea. Be it 10 images or 10k, you should have one canvas for drawing the image and one canvas for drawing the shapes. Image canvas need be touched only when the image changes. Different shapes can share the same canvas.
You should integrate a data storage. Local storage is clearly not a good option to store this amount of data (especially if you have a team member who also would be annotating on the same image dataset.)
Isolate the code to a separate-separate file according to the shape. It will be very handy when you will think of adding support for Circle, Polygon, Cuboidal, Point interactions. Trust me following OOPs concepts will relive you from a lot of pain.
In terms of complexity
zooming with coordinates is easy
move with coordinates is of medium level difficulty
but you need to think with pen and paper to implement move on a zoomed image canvas (P.S. take care of the canvas flickering when the image moves
). How much the image can move in each direction also need to be calculated.
Take care of the image to canvas dimension ratio because at the end you need to have the coordinates scaled down to image level.
If your canvas size vs image size ratio is 1:1 then your job is simplified.
But this won't happen always because some images might be very small or very large to directly fit in window screen and you need to scale up and down accordingly.
The complexity increases if you like to use percentage width and height for canvas and your other team member annotating the image has a different screen size. So he drawing something will look something else on your screen.

Html5 canvas and video

How can I make a canvas for the video to fit perfectly in the area
See picture
...It can't be done with native Html5 Canvas transformations.
You are trying to transform the display Canvas content (== your video) into a non-parallelogram -- which is not possible with native Canvas transformations. The Canvas can only be reshaped into parallelograms.
But...
You can skew the canvas to approximate your desired display.
The gold parallelogram in this image can be done with native Canvas transformations
Example code an a Demo:
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var cw=canvas.width;
var ch=canvas.height;
var angle=-Math.PI*.06;
var img=new Image();
img.onload=start;
img.src="https://dl.dropboxusercontent.com/u/139992952/multple/billboard1.jpg";
function start(){
cw=canvas.width=img.width;
ch=canvas.height=img.height;
ctx.drawImage(img,0,0);
ctx.transform(1,Math.tan(angle),0,1,0,0);
ctx.strokeStyle='gold';
ctx.lineWidth=4;
ctx.strokeRect(333,135,275,150);
}
<canvas id="canvas" width=300 height=300></canvas>
Drawing process
Prepare the background image offline by removing the red area making an alpha channel out of it instead, then use it like this:
Draw the video to canvas with transformation applied matching closely the shape plus a little overlap
Draw the background (or parts of it after first draw) on top of the video. This will mask the edges of the video that doesn't fit perfectly.
Transformation
Offline process:
Plot the points of the (now) alpha area so you have the coordinates, either a triangle or a quadrilateral. Note: canvas only support affine transformations (2D/parallelograms) so triangle has to be used. For CSS you can use 3D transforms with basis in a quadrilateral shape.
Normalize the values
In action:
Scale the canvas and the normalized values to the desired size
Apply transform, draw video, draw background as overlay on top of video
And since most video is max 30 frames per second you can also throttle the drawing loop to half to leave more resources for other things (use requestAnimationFrame() with a toggle flag).
Alternative approach:
Prepare a video with everything setup as you want. It should compress well since the surrounding areas don't change (use a long key-frame interval), and in this case the background doesn't contain much details due to low depth-of-field which also helps.

Reverse Clipping in Canvas

I want to clip html5 canvas so that I can achieve drawing result as per following image.
I want to achieve clip path such that all drawing will be performed only in black area.
Method 1
Assuming the white areas are transparent and the black is non-transparent then you can use composite mode:
ctx.globalCompositeOperation = 'source-in';
... draw graphics on top - only solid color will be affected ...
ctx.globalCompositeOperation = 'source-over'; // reset to default mode
A demo fiddle for this here
Method 2
Another simpler approach is to simply fill the canvas with the graphics you need then use clearRect() for those areas you want transparent.
This operation is fairly fast so there shouldn't be any flashing (and in case you can trigger this operation with a single requestAnimationFrame call).
A demo fiddle with clearRect
A demo fiddle with clearRect + requestAnimationFrame
Just note that calling rAF makes the code asynchronous but the purpose of using it is that your draw operations are synchronized within a frame update so flicker will be removed (if you should for some reason get problem with that).
Method 3
Create rectangle regions surrounding the area you want to preserve by a series of call to rect(). The set that as a clipping mask by using clip().
This techniques works best if the non-clipped areas are in a certain order or else you would have to define a lot of regions.
Remember to translate canvas 0.5 pixel first and only use integer values for the rectangles.
Method 4
Parse the pixel buffer manually to fill in pixels in the areas fulfilling the requirements, for example non-transparent pixels only.
Just be aware of that this is probably the slowest approach, it's affected by CORS restrictions (in case you draw an external image onto the canvas first) and it's more tedious if you want to fill in shapes, images, gradients and so forth which in case you would probably prefer an off-screen canvas to copy from.
There are other ways using different composite modes and drawing order to achieve the same result but I leave it with this as it should cover most scenarios.
You can use layering to fill your need:
make a copy of your image with all black made transparent
draw the original image on the canvas
draw your desired shapes
draw the transparent image on top
A Demo: http://jsfiddle.net/m1erickson/dFRUf/
This function creates a temporary canvas with the color-range you specify made transparent:
function makeImageTransparentByColor(image,r1,r2,g1,g2,b1,b2){
// create a temporary canvas and draw the image on the canvas
var bk=document.createElement("canvas");
var bkCtx=bk.getContext("2d");
bk.width=image.width;
bk.height=image.height
bkCtx.drawImage(image,0,0);
// get the pixel array from the canvas
var imgData=bkCtx.getImageData(0,0,bk.width,bk.height);
var data=imgData.data;
// loop through each pixel and make every pixel transparent
// that is between r1-r2, g1-g2 and b1-b2
for(var i=0;i<data.length;i+=4){
var r=data[i];
var g=data[i+1];
var b=data[i+2]
if(r>=r1 && r<=r2 && g>=g1 && g<=g2 && b>=b1 && b<=b2){
data[i]=0;
data[i+1]=0;
data[i+2]=0;
data[i+3]=0;
}
}
// put the modified pixels back on the canvas
bkCtx.putImageData(imgData,0,0);
// return the canvas with transparent image
return(bk);
}

AS3: How can I implement a perfect ROLL_OVER(or MOUSE_OVER) event listener on curved movieclips

I've a problem with ROLL_OVER event listener. When I enter the empty area withing the movieclip with mouse cursor, ROLL_OVER event triggers. But I want that event trigger only when mouse cursor is on the colored area.
To Make it more clear: Think about " O " letter, when mouse cursor is between the empty area of O letter (inside of O) , event shouldn't trigger. It should trigger only when mouse curser is on the black area.
How can I implement this?
Thanks
-Ozan
PROBLEM IS SOLVED THANKS TO #Ethan Kennerly
I just want to add a few things to help people have problem same as me. In my situation I tried to make continents glow when my mouse is over them. I used the ROLL_OVER/MOUSE_OVER eventlistener to check if my mouse is over them or not. But with the data given by Ethan Kennerly I produced another way.
In Ethan Kennerly's solution, if your mouse enters the area of continent from a transparent area , it doesn't get blur effect because ROLL_OVER and MOUSE_OVER event listeners only trigger once per enters so I used MOUSE_MOVE event listener on each continent movieclips.
And for this statement:
if (isPixelTransparent(DisplayObject(event.currentTarget), new Point(stage.mouseX, stage.mouseY)) {
return;
}
add whatever is in the "ROLL_OUT or MOUSE_OUT" eventlistener function, add all of them inside this statement. But don't remove ROLL_OUT or MOUSE_OUT functions.
It sounds like the movie clip contains a shape that has transparent pixels. Transparent pixels respond to mouse over and roll over. If you could draw vector graphics that have no shapes with transparent pixels, the mouse would ignore the empty space in the movie clip's bounding box.
Yet it sounds like you need to use transparent pixels and you want the mouse to ignore them, so you could guard, like this:
private function onRollOver(event:MouseEvent):void
{
if (isPixelTransparent(DisplayObject(event.currentTarget), new Point(stage.mouseX, stage.mouseY)) {
return;
}
// respond to roll over.
}
To detect transparency, Miguel Santirso rendered the pixels and translated the coordinate space here: http://sourcecookbook.com/en/recipes/97/check-if-a-pixel-is-transparent-in-a-displayobject (Except line 38 looks on my computer like "rect" got rendered as "ct"). You could optimize that code by only drawing the pixel in question, instead of the whole image, and checking if that pixel value (getPixel32) is 0, instead of calling a hitTest. I would optimize Miguel's code like this:
public static function isPixelTransparent(objectOnStage:DisplayObject, globalPoint:Point):Boolean
{
var local:Point = objectOnStage.globalToLocal(globalPoint);
var matrix:Matrix = new Matrix();
matrix.translate(-local.x, -local.y);
var data:BitmapData = new BitmapData(1, 1, true, 0x00000000);
data.draw(object, matrix);
return 0x00000000 == data.getPixel32(0, 0);
}
By the way, if all your movie clips would have the same hit test shape, you could create a separate transparent shape that listens to the roll over. I use a transparent shape to define a custom hit test shape that is a consistent and simple shape (like a circle) when the image is a more complicate shape (like an X or an O with nothing in the middle). The custom hit test shape is a Sprite with a transparent shape. The sprite listens to the roll over. A separate mouse listener shape is also useful if your movie clip, on later frames, creates new shapes that alter the silhouette of the movie clip.
The easiest solution would be using the Interactive PNG class by Moses.
http://blog.mosessupposes.com/?p=40
Normally the clear areas of a PNG are treated as solid, which can be especially frustrating when dealing with a lot of images that overlap each other because they tend to block mouse interactions on the clips below them.
This utility fixes that so that mouse events don't occur until you
bump against a solid pixel, or a pixel of any transparency value
besides totally clear. InteractivePNG lets you set an alphaTolerance
level to determine what transparency level will register as a hit.

Is it possible to create polygon shaped elements in HTML?

I am currently attempting to make a button which is in the shape of a trapezoid.
I found a method of creating the shape which involved CSS making borders and such.
The CSS method worked in the way that it made the shape, but I ran into an issue where the whole element is contained in a rectangle, so when you click in the white spaces outside of the trapezoid it will still register as a click in the element.
In short, I am trying to make the HTML element to be the shape, of a trapezoid, not just the visible shape itself. Thus when a user clicks any area around the button that is outside the visible Trapezoid, but may be within the actual boundaries of a button rectangle, it should ignore the click. Thanks.
Edit:
It was asked that I show an example of what I mean.
http://jsfiddle.net/MichaelMitchell/aR72g/9/
In this link, there is the red trapezoid, but you can see the background color is also green, and when you were to click the green it still activates an onclick. In other word, I only want the red to be able to trigger the onclick.
You cannot have other clickable areas than rectangles in HTML if you are not willing to do the trickery involving map attribute and image (see docs), but even then your image will always wrapped in rectangle bounding box (so you can only pretend to have different shape by using images with transparency and said map).
You can work around this by giving it an onmousemove event that determines whether or not that coordinate is actually inside the trapezoid and adds/removes the onclick event accordingly. Something like this:
<figure id ="trapezoid" onmousemove="trapezoidMouseMove(event)">
<p>Button</p>
</figure>
<script>
function trapezoidClick(e)
{
//Whatever you need it to do
alert("inside");
}
function trapezoidMouseMove(e)
{
//Fill in the angle of your trapezoid
angle = Math.PI / 4;
insideLeft = e.offsetX > Math.tan(angle) * e.offsetY;
insideRight = e.offsetX < e.toElement.offsetWidth - Math.tan(angle) * e.offsetY;
if (insideLeft && insideRight)
{
e.toElement.style.cursor = "pointer";
e.toElement.onclick = trapezoidClick;
}else{
e.toElement.style.cursor = "default";
e.toElement.onclick = null;
}
}
</script>