Our target is to export Mapbox as exported PNG format. Mapbox loaded into canvas, so our job get simplified. Give that map some time to load and fetch the image data when the load event is triggered. Usually there is a 'idle' event for map when we can determine that map event loaded fully. |
<div id="map-panel"> <div id="map"></div> </div> <div id="map-static"> <img src="" alt="??" id="imgTag"/> </div> |
body { margin: 0; padding: 0; } #map-panel { position: absolute; top: 0; bottom: 50%; width: 100%; padding:10px; } #map-panel #map { width: calc(100% - 20px); height: calc(100% - 20px); } #map-static { position: absolute; top: 50%; bottom: 0; width: 100%; padding:10px; } #imgTag { width: calc(100% - 20px); height: calc(100% - 20px); } |
mapboxgl.accessToken = 'pk.eyJ1IjoidGFrdX...fQ.57D0sXpw'; const map = new mapboxgl.Map({ container: 'map', style: 'mapbox://styles/mapbox/standard-beta', center: [-96, 37.8], zoom: 7, preserveDrawingBuffer: true, }); map.on('load', () => { console.log('Map.load'); map.loadImage("https://docs.mapbox.com/mapbox-gl-js/assets/cat.png", (error, image) => { if (error) { alert("Could not load image"); return; } map.addImage('cat_image', image); // Add a data source containing one point feature. map.addSource('point', { 'type': 'geojson', 'data': { 'type': 'FeatureCollection', 'features': [{ 'type': 'Feature', 'properties': {'name': 'Cat 1'}, 'geometry': { 'type': 'Point', 'coordinates': [-96, 37.8] } }, { 'type': 'Feature', 'properties': {'name': 'Cat 2'}, 'geometry': { 'type': 'Point', 'coordinates': [-96.40303, 37.8] } }] } }); // Add a layer to use the image to represent the data. map.addLayer({ 'id': 'layer-id-1', 'type': 'symbol', 'source': 'point', // reference the data source 'layout': { 'icon-image': 'cat_image', // reference the image 'icon-size': 0.15, "icon-allow-overlap": true, } }); }); map.on('idle', function () { console.log('Map.idle'); const canvasMap = map.getCanvas(); const dataUrl = canvasMap.toDataURL(); document.getElementById("imgTag").src = dataUrl; }); map.on('click', (e) => { // recognize clicked feature type console.log('Map.click'); const features = map.queryRenderedFeatures(e.point, { layers: ['layer-id-1'], }); if (features.length > 0) { new mapboxgl.Popup() .setLngLat(e.lngLat) .setHTML('<p>' + features[0].properties.name + '</p>') .addTo(map); } }); // Change the cursor to a pointer when the mouse is over the states layer. map.on('mouseenter', 'layer-id-1', () => { map.getCanvas().style.cursor = 'pointer'; }); // Change it back to a pointer when it leaves. map.on('mouseleave', 'layer-id-1', () => { map.getCanvas().style.cursor = ''; }); map.on('movestart', (e) => { console.log("Map.movestart"); }); map.on('moveend', (e) => { console.log("Map.moveend"); }); }); |
Check this link for more options how to control mouse click event |
Showing posts with label canvas. Show all posts
Showing posts with label canvas. Show all posts
Tuesday, September 19, 2023
How to Save a Mapbox GL Web Map Extent as an Image | Mapbox GL JS: Export map to PNG
Saturday, September 16, 2023
Cropping Images in JavaScript | Crop an Image in JavaScript With HTML Canvas
Digital images are composed of a two dimensional array as well as grid of vertical and horizontal pixels, small color squares each called pixel. Image cropping is a way of image editing that involves selecting a portion of an image, hence reducing the number of pixels and changing the aspect ratio as well as size. |
A canvas is a html element which is a white region in which you can display or draw graphical elements in modern web browsers. A common way to crop an image in JavaScript is with the HTML5 <canvas> element and then transform the images by calling the drawImage() function respectively. |
Step 1: Create a Canvas in HTML Create a <canvas> element in your HTML document using below code: <canvas id="mycanvas" width="800px" height="400px"></canvas> |
Step 2: Create a JavaScript File and a Crop Function Define a function named cropImage(), which you can call from within your code when an image loaded from some source or from base64 string. Add the onload() function to the Image object so that cropImage() runs only after an image is fully loaded on the viewer’s browser. onload() gets the <canvas> element from your HTML and then will prepare a 2D context object for the canvas. const canvas = document.getElementById('mycanvas'); const context = canvas.getContext('2d'); |
Step 3: Load the Image Create an image object from any source you want and load an image with the src property from a local drive or the internet or base64 string as per your requirement. var image = new Image(); image.src = "https://static.image.com/img.jpg"; |
Step 4: Call the drawImage() Function Here’s the syntax of the drawImage() function when Image object loaded: drawImage(image, sx, sy, sWidth, sHeight, dx, dy, dWidth, dHeight); Crop operations require all nine parameters described below:
image.onload = function() { context.drawImage(image, 100, 100, 200, 200, 50,50, 200, 200); } drawImage() performs two steps for further process:
|
Below is another solid example of how we can crop image:
const image = new Image(); image.crossOrigin='anonymous'; image.onload = () => { const canvas: any = document.createElement('canvas'); const ctx: any = canvas.getContext('2d'); canvas.height = image.naturalHeight - 25; // above line will crop out 25px from bottom canvas.width = image.naturalWidth; ctx.drawImage(image, 0, 0); const dataUrl: any = canvas.toDataURL(); // dataUrl is base64 encoded value of cropped image }; image.onerror = function() { alert("Failed to process image"); }; image.src = "https://static.image.com/hello.png"; |
Monday, July 22, 2013
Facebook Canvas Tutorial
Creating your App
Start by visiting the App Dashboard. If you haven't created an application before you will be prompted to register. Note that you have to verify your Facebook account to create apps on Facebook.
Configuring your App
Apps on Facebook are loaded into the Canvas section of the Canvas Page. The Canvas is quite literally a blank canvas within Facebook on which to run your app. You populate the Canvas by providing a Canvas URL that contains the HTML, JavaScript and CSS that make up your app. When a person using your app requests the Canvas Page, we load the Canvas URL within an
iframe
on that page. This results in your app being displayed within the standard Facebook chrome.
For example, suppose that you have a web app available at
//www.example.com/canvas
. This is your Canvas URL. When you set up your app on Facebook, you must specify a Canvas Page name that is appended to //apps.facebook.com/. You can specify this by entering a unique name in the App Namespace
field through the App Dashboard. In this example, we'll useyour_app
as the Canvas Page name. When someone using your app navigates to //apps.facebook.com/your_app
, they'll see the contents of www.example.com/canvas
loaded inside of Facebook.com.
Note that
www.example.com/canvas
cannot forward to another URL via HTTP redirect responses, for example response code 301, but has to return the response directly.
Once you've created a Facebook app, go to the App on Facebook section and specify a Canvas and Secure Canvas URL:
Because your app is loaded in the context of Facebook, you must be aware of certain size constraints when designing your user interface. You can manage settings for the size of your iframe in the Dev App on Facebook settings.
Canvas width
You can set your Canvas Width to Fixed (760px), the default setting, which makes your app have a fixed width of 760 pixels. You can also set your width to Fluid, which means that we set the iframe width to 100%. Your content will then be left-aligned and resize to fill the page as the user changes the width of their browser.
Canvas height
You can set the Canvas height to Fluid, the default setting, in which case the iframe height is set to 100% which means that it grows the fill the page and shows scroll-bars if your content exceeds the height of the page.
You can also set the height to Settable, in which case the height of the Canvas defaults to 800 pixels. You can change the height of the iframe by calling the FB.Canvas.setSize() method to fit your content. You can also call FB.Canvas.setAutoGrow() to enable Auto-grow functionality where you poll for the height of your content and grow the height of the parent iframe to match accordingly. Note these methods only work with Canvas height set to Settable.
Configuring for App Center
Once you have configured your app for Canvas, the next step is to configure the App Center settings. App Center is the central location for people to discover and try out new apps and a primary source of installs. Configuring these settings will allow you to customize your App Detail page to display your app description, icons, screenshots and other relevant promotional materials in the Facebook App Center. For more information on this step, see the App Center docs.
Authorization
In order to create a personalized user experience, Facebook sends your app information about the user. This information is passed to your Canvas URL using HTTP POST within a single signed_request parameter which contains a base64url encoded JSON object.
When someone first accesses your app, the signed_request parameter contains a limited amount of user data:
Name | Description |
---|---|
user | A JSON array containing the locale string, country string and the age object (containing the min and max numbers of the age range) for the current person using the app. |
algorithm | A JSON string containing the mechanism used to sign the request. |
issued_at | A JSON number containing the Unix timestamp when the request was signed. |
In order for you to gain access to all the information available to your app by default (like Facebook ID), people must authorize your app. We recommend that you use the Login Dialog for apps on Facebook.com. You invoke this dialog by redirecting the browser to the following URL (replacing the YOUR_APP_ID and YOUR_CANVAS_PAGE with the correct values found in the App Dashboard):
https://www.facebook.com/dialog/oauth?
client_id=YOUR_APP_ID&redirect_uri=YOUR_CANVAS_PAGE
Because of the way iframes are currently loaded for apps on Facebook.com, it's important that you navigate the top window of the browser to the Login dialog. Many apps do this by sending a
script
fragment to the browser setting the top.location.href
property to the dialog URL. Please see the PHP example at the end of this section for an example.
By default, people using your app are asked to authorize the app to access their public profile. If your app needs more than this information to work correctly, you must request specific permissions from people. This is accomplished by adding a scope parameter to the Login dialog request followed by comma separated list of the required permissions. The following example shows how to ask for access to someone's email address and News Feed:
https://www.facebook.com/dialog/oauth?client_id=YOUR_APP_ID
&redirect_uri=YOUR_CANVAS_PAGE&scope=email,read_stream
A full list of permissions is available in our permissions reference. There is a strong inverse correlation between the number of permissions your app requests and the number of users that will allow those permissions. The greater the number of permissions you ask for, the lower the number of users that will grant them; so we recommend that you only request the permissions you absolutely need for your app.
If people press click Don't Allow, your app is not authorized. The Login dialog redirects (via HTTP 302) to the URL you passed in the redirect_uri parameter with the following error information:
http://YOUR_CANVAS_PAGE?error_reason=user_denied&
error=access_denied&error_description=The+user+denied+your+request
If people click Allow, your app is authorized. The Login dialog redirects (via HTTP 302) to the URL you passed in the redirect_uriparameter. After the app has been authorized, the signed_request parameter will contain the following information on subsequent requests:
Name | Description |
---|---|
user | A JSON array containing the locale string, country string and the age object (containing the min and max numbers of the age range). |
algorithm | A JSON string containing the mechanism used to sign the request. |
issued_at | A JSON number containing the Unix timestamp when the request was signed. |
user_id | A JSON string containing the person's Facebook user identifier (UID). |
oauth_token | A JSON string that you can pass to the Graph API. |
expires | A JSON number containing the Unix timestamp when the oauth_token expires. |
The following PHP example demonstrates how to access the
signed_request
parameter and prompt the user to authorize your app: $app_id = "YOUR_APP_ID";
$canvas_page = "YOUR_CANVAS_PAGE_URL";
$auth_url = "//www.facebook.com/dialog/oauth?client_id="
. $app_id . "&redirect_uri=" . urlencode($canvas_page);
$signed_request = $_REQUEST["signed_request"];
list($encoded_sig, $payload) = explode('.', $signed_request, 2);
$data = json_decode(base64_decode(strtr($payload, '-_', '+/')), true);
if (empty($data["user_id"])) {
echo("<script> top.location.href='" . $auth_url . "'</script>");
} else {
echo ("Welcome User: " . $data["user_id"]);
}
You can learn more about the
signed_request
parameter including how to validate the signature in our Signed Request Referenceguide. Several of our SDKs, such as the JavaScript SDK and the PHP SDK make authentication and authorization straightforward.
Once someone has authorized your application, you can start using the Graph API to access that person's profile information as well as friend data.
Social channels
Facebook provides a number of different ways for people to share with their friends from your app. We call these social channels. Your app can publish directly to a person's News Feed, send Requests to their friends and leverage our automatic channels.
Feed
The News Feed is shown immediately to people when they go to Facebook, making it core to the Facebook experience. Your app can post to the News Feed, that is, share something with other people, by using the Feed dialog. The following example shows how to display this dialog within your Canvas Page:
$app_id = "YOUR_APP_ID";
$canvas_page = "YOUR_CANVAS_PAGE_URL";
$message = "Apps on Facebook.com are cool!";
$feed_url = "//www.facebook.com/dialog/feed?app_id="
. $app_id . "&redirect_uri=" . urlencode($canvas_page)
. "&message=" . $message;
if (empty($_REQUEST["post_id"])) {
echo("<script> top.location.href='" . $feed_url . "'</script>");
} else {
echo ("Feed Post Id: " . $_REQUEST["post_id"]);
}
Requests
Requests are a great way to enable people to invite their friends to your app or to take specific action like accept a gift or help complete a task. Your app can send requests by using the Request dialog. The following example shows how to display this dialog within your Canvas Page:
$app_id = "YOUR_APP_ID";
$canvas_page = "YOUR_CANVAS_PAGE_URL";
$message = "Would you like to join me in this great app?";
$requests_url = "//www.facebook.com/dialog/apprequests?app_id="
. $app_id . "&redirect_uri=" . urlencode($canvas_page)
. "&message=" . $message;
if (empty($_REQUEST["request_ids"])) {
echo("<script> top.location.href='" . $requests_url . "'</script>");
} else {
echo "Request Ids: ";
print_r($_REQUEST["request_ids"]);
}
If you prefer to have your app send requests directly to people
(that is, to make an app-generated request), you post a request to
theapprequest
connection of theUser
Graph object:
$app_id = YOUR_APP_ID;
$app_secret = YOUR_APP_SECRET;
$token_url = "//graph.facebook.com/oauth/access_token?" .
"client_id=" . $app_id .
"&client_secret=" . $app_secret .
"&grant_type=client_credentials";
$app_access_token = file_get_contents($token_url);
$user_id = THE_CURRENT_USER_ID;
$apprequest_url ="//graph.facebook.com/" .
$user_id .
"/apprequests?message='INSERT_UT8_STRING_MSG'" .
"&data='INSERT_STRING_DATA'&" .
$app_access_token . "&method=post";
$result = file_get_contents($apprequest_url);
echo("App Request sent?", $result);
The message parameter is a UTF-8 string that describes the request. The data parameter is a string that the app can use to store any relevant data in order to process the request.
Once a new request is sent to someone, they see it as a counter on the app bookmark, and it also increments the counter next to the appropriate Dashboard.
If you would like to send an app-generated request to more than one person, you can use the
ids
parameter (see Selection in the Graph API) and enter a comma delimited string of people's IDs:POST https://graph.facebook.com/apprequests?ids=user_id1,user_id2<br> &message=Hello&access_token=APP ACCESS TOKEN
Samples and next steps
If you're interested in building Facebook games, see our Games Tutorial, which walks you through implementing authorization, invites, feed stories, scores and achievements. It's a great place to get started.
This was a quick survey of the major integration points available to Facebook apps. Beyond these features, you can leverage all the different pieces of Facebook Platform including social plugins and the Graph API within your app. See Overview of the Facebook Platform for a complete summary of Facebook developer tools.
Please see our Integrating with Canvas for additional advanced best practices when integrating with Canvas.
Subscribe to:
Posts (Atom)