Download the code: https://github.com/blackberry/WebWorks-Samples/tre
Figure 1: Screenshot of SketchPad application
Example: Drawing a line on a canvas:
function drawPen(x, y)
{
var ctx = canvas.getContext("2d");
ctx.lineWidth = 2;
ctx.strokeStyle = "#00F";
ctx.beginPath();
ctx.moveTo(lastX, lastY);
ctx.lineTo(x, y);
ctx.stroke();
}
Touch events are supported by overriding the default event handlers ontouchstart, ontouchmove and ontouchend. The application reads the current X and Y coordinates for each event and calls the drawPen() method whenever an incremental line should be drawn to the screen.
Example: Supporting the TouchStart and TouchMove events:
document.ontouchstart = function(event)
{
//prevents the browser container from scrolling:
event.preventDefault();
//Get position of current touch event
var touchEvent = event.changedTouches[0];
if (touchEvent.pageX || touchEvent.pageY) {
//Initialize the starting position:
lastX = touchEvent.pageX;
lastY = touchEvent.pageY;
}
}
document.ontouchmove = function(event)
{
//prevents the browser container from scrolling:
event.preventDefault();
//Get position of current touch event
var touchEvent = event.changedTouches[0];
if (touchEvent.pageX || touchEvent.pageY)
{
//draw a line between the last and current touch positions
drawPen(touchEvent.pageX, touchEvent.pageY);
}
}
The sketchpad application uses a custom JavaScript® extension to capture an image of the current screen and save it as a PNG to the file system. This extension can be found within the “ext” folder of the project.
Example: Using a custom JavaScript extension to take a screenshot:
function takeScreenshot()
{
//Generate the name of the file to be created
var fileName = getFileName();
//Call the capture() method of the JavaScript Extension
if (extensions.screenshot.capture(fileName)) {
alert("Screen image saved:\n" + fileName);
}
}
The entire source code for this sample application is published in the WebWorks-Samples repo of the BlackBerry Open Source project in Github.
Links: