EzDevInfo.com

canvas interview questions

Top canvas frequently asked interview questions

How do I get the coordinates of a mouse click on a canvas element?

What's the simplest way to add a click event handler to a canvas element that will return the x and y coordinates of the click (relative to the canvas element)?

No legacy browser compatibility required, Safari, Opera and Firefox will do.


Source: (StackOverflow)

Canvas width and height in HTML5

Is it possible to fix the width and height of a canvas element with some variables? I am speaking of such canvas elements that only exist in Html 5.

The usual way is the following :

<canvas id="canvas" width="300" height="300"></canvas>

Source: (StackOverflow)

Advertisements

How can I write text on a HTML5 canvas element?

Is it possible to write text on HTML5 canvas?


Source: (StackOverflow)

How can I use the HTML5 canvas element in IE?

I am trying to use the HTML5 canvas element to draw some arcs and circles - this works perfectly in FF but IE8 does not seem to support it.

Now, there exist Javascript libraries which seem to make IE8 work well with Canvas. An example can be found here.

I have read their entire source but I cannot understand how they are making Canvas work with IE8. Can somebody please throw some light on the method used?


Source: (StackOverflow)

Map Tiling Algorithm

The Map

I'm making a tile based RPG with Javascript, using perlin noise heightmaps, then assigning a tile type based on the height of the noise.

The maps end up looking something like this (in the minimap view).

enter image description here

I have a fairly simple algorithm which extracts the color value from each pixel on the image and converts it into a integer (0-5) depending on its postion between (0-255) which corresponds to a tile in tile dictionary. This 200x200 array is then passed to the client.

The engine then determines the tiles from the values in the array and draws them to the canvas. So, I end up with interesting worlds that have realistic looking features: mountains, seas etc.

Now the next thing I wanted to do was to apply some kind of blending algorithm that would cause tiles to seamlessly blend into their neighbours, if the neighbour is not of the same type. The example map above is what the player sees in their minimap. Onscreen they see a rendered version of the section marked by the white rectangle; where the tiles are rendered with their images rather than as single color pixels.

This is an example of what the user would see in the map but it is not the same location as the viewport above shows!

enter image description here

It is in this view that I want the transitioning to occur.

The Algorithm

I came up with a simple algorithm that would traverse the map within the viewport and render another image over the top of each tile, providing it was next to a tile of different type. (Not changing the map! Just rendering some extra images.) The idea of the algorithm was to profile the current tile's neighbors:

An example of a tile profile

This is an example scenario of what the engine might have to render, with the current tile being the one marked with the X.

A 3x3 array is created and the values around it are read in. So for this example the array would look like.

[
    [1,2,2]
    [1,2,2]
    [1,1,2]
];

My idea was then to work out a series of cases for the possible tile configurations. On a very simple level:

if(profile[0][1] != profile[1][1]){
     //draw a tile which is half sand and half transparent
     //Over the current tile -> profile[1][1]
     ...
}

Which gives this result:

Result

Which works as a transition from [0][1] to [1][1], but not from [1][1] to [2][1], where a hard edge remains. So I figured that in that instance a corner tile would have to be used. I created two 3x3 sprite sheets that I thought would hold all the possible combinations of tiles that could be needed. Then I replicated this for all of the tiles that there are in the game (The white areas are transparent). This ends up being 16 tiles for each type of tile (The center tiles on each spritesheet are not used.)

SandSand2

The Ideal Outcome

So, with these new tiles and the correct algorithm, the example section would look like this:

Correct

Every attempt I have made has failed though, there is always some flaw in the algorithm and the patterns end up strange. I can't seem to get all the cases right and overall it seems like a poor way of doing it.

A Solution?

So, if anyone could provide an alternative solution as to how I could create this effect, or what direction to go for writing the profiling algorithm, then I would be very grateful!


Source: (StackOverflow)

Best way to detect that HTML5 is not supported

The standard way to deal with situations where the browser does not support the HTML5 <canvas> tag is to embed some fallback content like:

<canvas>Your browser doesn't support "canvas".</canvas>

But the rest of the page remains the same, which may be inappropriate or misleading. I'd like some way of detecting canvas non-support so that I can present the rest of my page accordingly. What would you recommend?


Source: (StackOverflow)

How can you find the height of text on an HTML canvas?

The spec has a context.measureText(text) function that will tell you how much width it would require to print that text, but I can't find a way to find out how tall it is. I know it's based on the font, but I don't know to convert a font string to a text height.


Source: (StackOverflow)

HTML5 Canvas Resize (Downscale) Image High Quality?

I use html5 canvas elements to resize images im my browser. It turns out that the quality is very low. I found this: Disable Interpolation when Scaling a <canvas> but it does not help to increase the quality.

Below is my css and js code as well as the image scalled with Photoshop and scaled in the canvas API.

What do I have to do to get optimal quality when scaling an image in the browser?

Note: I want to scale down a large image to a small one, modify color in a canvas and send the result from the canvas to the server.

CSS:

canvas, img {
    image-rendering: optimizeQuality;
    image-rendering: -moz-crisp-edges;
    image-rendering: -webkit-optimize-contrast;
    image-rendering: optimize-contrast;
    -ms-interpolation-mode: nearest-neighbor;
}

JS:

var $img = $('<img>');
var $originalCanvas = $('<canvas>');
$img.load(function() {


   var originalContext = $originalCanvas[0].getContext('2d');   
   originalContext.imageSmoothingEnabled = false;
   originalContext.webkitImageSmoothingEnabled = false;
   originalContext.mozImageSmoothingEnabled = false;
   originalContext.drawImage(this, 0, 0, 379, 500);
});

The image resized with photoshop:

enter image description here

The image resized on canvas:

enter image description here

Edit:

I tried to make downscaling in more than one steps as proposed in:

Resizing an image in an HTML5 canvas and Html5 canvas drawImage: how to apply antialiasing

This is the function I have used:

function resizeCanvasImage(img, canvas, maxWidth, maxHeight) {
    var imgWidth = img.width, 
        imgHeight = img.height;

    var ratio = 1, ratio1 = 1, ratio2 = 1;
    ratio1 = maxWidth / imgWidth;
    ratio2 = maxHeight / imgHeight;

    // Use the smallest ratio that the image best fit into the maxWidth x maxHeight box.
    if (ratio1 < ratio2) {
        ratio = ratio1;
    }
    else {
        ratio = ratio2;
    }

    var canvasContext = canvas.getContext("2d");
    var canvasCopy = document.createElement("canvas");
    var copyContext = canvasCopy.getContext("2d");
    var canvasCopy2 = document.createElement("canvas");
    var copyContext2 = canvasCopy2.getContext("2d");
    canvasCopy.width = imgWidth;
    canvasCopy.height = imgHeight;  
    copyContext.drawImage(img, 0, 0);

    // init
    canvasCopy2.width = imgWidth;
    canvasCopy2.height = imgHeight;        
    copyContext2.drawImage(canvasCopy, 0, 0, canvasCopy.width, canvasCopy.height, 0, 0, canvasCopy2.width, canvasCopy2.height);


    var rounds = 2;
    var roundRatio = ratio * rounds;
    for (var i = 1; i <= rounds; i++) {
        console.log("Step: "+i);

        // tmp
        canvasCopy.width = imgWidth * roundRatio / i;
        canvasCopy.height = imgHeight * roundRatio / i;

        copyContext.drawImage(canvasCopy2, 0, 0, canvasCopy2.width, canvasCopy2.height, 0, 0, canvasCopy.width, canvasCopy.height);

        // copy back
        canvasCopy2.width = imgWidth * roundRatio / i;
        canvasCopy2.height = imgHeight * roundRatio / i;
        copyContext2.drawImage(canvasCopy, 0, 0, canvasCopy.width, canvasCopy.height, 0, 0, canvasCopy2.width, canvasCopy2.height);

    } // end for


    // copy back to canvas
    canvas.width = imgWidth * roundRatio / rounds;
    canvas.height = imgHeight * roundRatio / rounds;
    canvasContext.drawImage(canvasCopy2, 0, 0, canvasCopy2.width, canvasCopy2.height, 0, 0, canvas.width, canvas.height);


}

Here is the result if I use a 2 step down sizing:

enter image description here

Here is the result if I use a 3 step down sizing:

enter image description here

Here is the result if I use a 4 step down sizing:

enter image description here

Here is the result if I use a 20 step down sizing:

enter image description here

Note: It turns out that from 1 step to 2 steps there is a large improvement in image quality but the more steps you add to the process the more fuzzy the image becomes.

Is there a way to solve the problem that the image gets more fuzzy the more steps you add?

Edit 2013-10-04: I tried the algorithm of GameAlchemist. Here is the result compared to Photoshop.

PhotoShop Image:

PhotoShop Image

GameAlchemist's Algorithm:

GameAlchemist's Algorithm


Source: (StackOverflow)

What's the best way to set a single pixel in an HTML5 canvas?

The HTML5 Canvas has no method for explicitly setting a single pixel.

It might be possible to set a pixel using a very short line, but then antialising and line caps might interfere.

Another way might be to create a small ImageData object and using:

context.putImageData(data, x, y)

to put it in place.

Can anyone describe an efficient and reliable way of doing this?


Source: (StackOverflow)

HTML5 Canvas 100% Width Height of Viewport?

I am trying to create a canvas element that takes up 100% of the width and height of the viewport.

You can see in my example here that is occurring, however it is adding scroll bars in both Chrome and FireFox. How can I prevent the extra scroll bars and just provide exactly the width and height of the window to be the size of the canvas?


Source: (StackOverflow)

How to clear the canvas for redrawing

After experimenting with composite operations and drawing images on the canvas I'm now trying to remove images and compositing. How do I do this?

I need to clear the canvas for redrawing other images; this can go on for a while so I don't think drawing a new rectangle every time will be the most efficient option.


Source: (StackOverflow)

Capture HTML Canvas as gif/jpg/png/pdf?

Is it possible to capture or print what's displayed in an html canvas as an image or pdf?

I'd like to generate an image via canvas, and be able to generate a png from that image.


Source: (StackOverflow)

Capture Signature using HTML5 and iPad

Anyone know how this can be done? Would you use a canvas object, svg, jQuery, etc?


Source: (StackOverflow)

jQuery equivalent of getting the context of a Canvas

I have the following working code:

ctx = document.getElementById("canvas").getContext('2d');

Is there any way to re-write it to use $? Doing this fails:

ctx = $("#canvas").getContext('2d');

Source: (StackOverflow)

What is the current state of the art in HTML canvas JavaScript libraries and frameworks? [closed]

I am currently investigating options for working with the canvas in a new HTML 5 application, and was wondering what is the current state of the art in HTML canvas JavaScript libraries and frameworks?

In particular, are there frameworks that support the kind of things needed for game development - complex animation, managing scene graphs, handling events and user interactions?

Also willing to consider both commercial and open source products.


Source: (StackOverflow)