How to program pressing different buttons for different effects in Javascript - javascript

I am taking a beginner class in coding and need help with an issue I'm coming across in a project that I am making...
function start() {
//Creates the jester image, describing text and the selectable key for them
var rect = new Rectangle(200, 120);
rect.setPosition(0, 0);
rect.setColor(Color.grey);
add(rect);
var jester = new WebImage("data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wCEAAkGBxITEhMTExIVFhUXFhUWFRcXFRUWFRcVFxUXFhUVFRUYHSggGBolHRUVITEhJSkrLi4uFx8zODMtNygtLisBCgoKDg0OGxAQGy0lICUtLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLf/AABEIAOEA4QMBIgACEQEDEQH/xAAcAAACAgMBAQAAAAAAAAAAAAAEBQMGAAIHAQj/xAA7EAABAwIFAgQDBgUDBQEAAAABAAIDBBEFEiExQQZREyJhcTKBkQcUobHB8BUjM0LRUnLhNGKCkvEW/8QAGQEAAwEBAQAAAAAAAAAAAAAAAQIDBAAF/8QALhEAAgICAgEEAQIEBwAAAAAAAAECEQMhEjFBBBMiUTIUcWHB8PEFM0KBgpGh/9oADAMBAAIRAxEAPwCtPh8hyygttsdx7JEDp6Jq+gksfKSO6GNDxyVjk5S2kbZY5z3FdEdNhocQ5MazDZJA0NAIuAdbEC++qhoqV0Y0d+/ZG0GJSOk8MgWALr86KWSeJrlJNNEJwS/KNHtSP5wBBABaBxoEp6jqhl/3Pv8ARN3Yk6xDrPFzuBoOwO91VeoHNc9mQ6AatO7SfzHqs2DFHmnF9fZFr6IPCs0uCv2E4Xaki8KZhjDM8mYhuWY6n33VChqdQyysFQAxjIx/uctOd1Gn5BGVB9DWQwtc57RI8E2J+H3CQYvi8tQbuPlHwtGw9lFXSF5yjYI+jom5NVNfCPJhllbXHwKaGHMdduUbPr5W7BGRQt2A05W1QwNFmjU7BGMk5cmTvwKS539Ng1KybCmwgOkddx1I7KxYXhwiBe7V52CArMPMjyXa8rvf5PX4/f2O6Wg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2YN/TCxYvZl4PUx9hTOVUepNysWKngGTosvT/8AQZ7IibhYsWYRdHlP8Y9wm1J/1Y9j+SxYvP8AWfl/xkTn/IsVX/QPzVC7rFih/hX+r9o/zFxdM1CIh5WLF7DKI1bt8167dYsXAGFJsVLUfCPcLFiXyMa0u5+aLi591ixEB4PhP+4KcbfL9FixcBA5/pj2P5qKbZYsS+RjMJ3d7FFu2WLFhz/5kf3L4/xYPBz8/wAkyg+EfvhYsVMXQnhEtZ/Sb8/zXNeo/wDqT7BYsVc3TM8/xI1ixYvNMh//2Q==");
jester.setSize(200, 120);
jester.setPosition(0, 0);
add(jester);
var txt = new Text("Describing text!", "15pt Arial");
txt.setPosition(230, 30);
txt.setColor(Color.blue);
add(txt);
//Creates the king image, describing text and the selectable key for them
var rect = new Rectangle(200, 120);
rect.setPosition(0, 120);
rect.setColor(Color.green);
add(rect);
var king = new WebImage("data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wCEAAkGBxITEhMTExIVFhUXFhUWFRcXFRUWFRcVFxUXFhUVFRUYHSggGBolHRUVITEhJSkrLi4uFx8zODMtNygtLisBCgoKDg0OGxAQGy0lICUtLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLf/AABEIAOEA4QMBIgACEQEDEQH/xAAcAAACAgMBAQAAAAAAAAAAAAAEBQMGAAIHAQj/xAA7EAABAwIFAgQDBgUDBQEAAAABAAIDBBEFEiExQQZREyJhcTKBkQcUobHB8BUjM0LRUnLhNGKCkvEW/8QAGQEAAwEBAQAAAAAAAAAAAAAAAQIDBAAF/8QALhEAAgICAgEEAQIEBwAAAAAAAAECEQMhEjFBBBMiUTIUcWHB8PEFM0KBgpGh/9oADAMBAAIRAxEAPwCtPh8hyygttsdx7JEDp6Jq+gksfKSO6GNDxyVjk5S2kbZY5z3FdEdNhocQ5MazDZJA0NAIuAdbEC++qhoqV0Y0d+/ZG0GJSOk8MgWALr86KWS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VyWbpu5u0ua8G4sOUynGIkxuDmeTQi583v2TWdR2Gkq2nnVGNmAXLqXGq0Mt4TM22bPoPwujJqyre1o8Vjb6ENab/APsUeaR3FhXXTo5JW2NyG2Njtqq7FC47A6eibMp/DFiY3O5JP691HNmaAW2ab6WN1CSUnZSOkBwUrnEho19dERJh0jdfLb3uVtlc73vqbjnvYrapgc22Y6+/HyUuagU4tghaefyRMDbt0Gv4LeNrCQHH5gHRFU0DQdD9Ujk5qkFLi9mkkRbGLjUn5WVL6s+IDhdAxK3ht91zzqR95beiORuMCGZ6YgyBYjfu69WT3GY+TFeN/F/5K2YN/TCxYvZl4PUx9hTOVUepNysWKngGTosvT/8AQZ7IibhYsWYRdHlP8Y9wm1J/1Y9j+SxYvP8AWfl/xkTn/IsVX/QPzVC7rFih/hX+r9o/zFxdM1CIh5WLF7DKI1bt8167dYsXAGFJsVLUfCPcLFiXyMa0u5+aLi591ixEB4PhP+4KcbfL9FixcBA5/pj2P5qKbZYsS+RjMJ3d7FFu2WLFhz/5kf3L4/xYPBz8/wAkyg+EfvhYsVMXQnhEtZ/Sb8/zXNeo/wDqT7BYsVc3TM8/xI1ixYvNMh//2Q==");
king.setSize(200, 120);
king.setPosition(0, 120);
add(king);
var txt = new Text("Describing text!", "15pt Arial");
txt.setPosition(230, 140);
txt.setColor(Color.blue);
add(txt);
keyDownMethod(jesterSelect);
keyDownMethod(kingSelect);
}
function jesterSelect(e) {
if(e.keyCode == Keyboard.letter('J')){
removeAll();
var circle = new Circle(50);
circle.setPosition(100, 200);
circle.setColor(Color.blue);
add(circle);
}
}
function kingSelect(e) {
if(e.keyCode == Keyboard.letter('N')){
removeAll();
var circle = new Circle(50);
circle.setPosition(100, 200);
circle.setColor(Color.red);
add(circle);
}
}
Right now I have images displayed of a jester and a king and depending on what button you press you are directed to new "slide". As of now, the program only responds when I press the "k" key and doesn't respond and create the blue circle when I press the "j" key. I've determined that whatever is put last in the start function determines what actually works, but I want the user to be able to press any of the interactive keys and be displayed with a different outcome. I would appreciate any help since I've been stuck on this for a while now, thank you!

You need to capture the keydown event.
Add this to your init code:
window.addEventListener("keydown", keyHandler);
and modify this block for all of your key events:
function KeyHandler(e)
{
switch (e.keyCode)
{
case 32: // space
{
// dostuff
break;
}
case 37: // left arrow
{
// dostuff
break;
}
}
}

Related

Paper.js Background Rasterization Glitches

We are building an image editor of sorts using Paper.js. We have a queue on the side of the Paper.js canvas that allows switching between images. Each time we switch between images, we want to flatten all the annotations (rasterize) onto the image just being edited.
Each time we switch images, this method is called, which rasterizes the current image and annotations to a data URL. (If we revisit this image, a raster from this data URL will be displayed.)
var flattenToDataUrl = function() {
layerAsRaster = paper.project.layers[0].rasterize(); // Layer to Paper.js Raster object
layerAsRaster.visible = false; // Attempt to set not visible
var dataString = layerAsRaster.toDataURL();
return dataString;
};
Then we end up calling this method, which changes out the image we're editing:
var setCanvasImage = function(imageObject) {
if(imageObject != null)
{
imageHeight = imageObject.height;
var imageWidth = imageObject.width;
// Set up HTMLImage
var imageElement = new Image(imageObject.width, imageObject.height);
if(_.has(imageObject, 'imageData')) { // Came as 64 bit data
imageElement.src = 'data:image/png;base64,' + imageObject.imageData;
} else if(_.has(imageObject, 'imageUrl')) { // Came as URL
imageElement.src = imageObject.imageUrl;
}
// Add image to Paper.js canvas
imageElement.onload = function(event) {
// Initialize Paper.js on the canvas
paper.setup(canvas);
raster = new paper.Raster(imageElement, new paper.Point(canvas.width / 2, canvas.height / 2));
setUpNotes();
selectedItems = new paper.Group(); // Since Paper.js has been setup we can now initialize this Group
registerCanvasEvents(); // Panning, zooming, moving selected items, deselecting all selected items
fitToPage();
};
}
};
So, this changes out the image, but when I move my mouse into the canvas after selecting a different image in the queue, it glitches to the image we were just on (with its annotations) until I do something like pan, zoom, etc. Then I see the image I selected and am truly working with.
Removing the flattenToDataUrl() functionality makes the queue work seamlessly. So it seems to me something is fishy there. We are generating a Paper.js Raster object in that method. Rasters seem to automatically add themselves. I attempt to curb this with a call to
layerAsRaster.visible = false;
but to no avail.
What is causing this glitchy behavior and how do I prevent it?
Update
For clarity (hopefully) and completeness, I've decided to post the whole PaperFunctions class we use in conjunction with React, which hosts our <canvas> element. There's a lot of code, and a lot of cleanup to do, especially in registerCanvasEvents(). Bear with this learning beginner. Also it's several hundred lines, so it may be helpful to paste it into your favorite editor. Entry points include setCanvas which is called in componentDidMount of the React class with the <canvas> element, and canvasSetImage which is called from the queue. I agree from bmacnaughton's answer that it's weird to call paper.setup(canvas) every time we load a new image. I'm currently investigating the right solution to this, the right place to put it. setCanvas seems logical but when I drag the image to move it in that setup, it leaves a trail of images in its wake. Anyway, here's PaperFunctions.js:
var JQueryMousewheel = require('jquery-mousewheel')($);
var SimplePanAndZoom = require('./SimplePanAndZoom.js');
var panAndZoom = new SimplePanAndZoom();
var selectedItems;
// We use selection here in two distinct ways.
// An item may be Paper.js selected but not in the selection group.
// This is because we want to show it is selectable.
// A blue bounding box indicates it is selectable.
// A green bounding box indicates it has actually been selected and added to selectedItems.
// Only things in selectedItems are actually operated on.
// So the event handlers in this method basically set up whether or not the item is in selectedItems (and therefore will be operated on for moving, resizing, deleting, etc.).
// That is, the event handlers here are concerned with displaying to the user the status of selection for the item - whether or not it will be operated on when events actually happen on the selectedItems Group.
var registerItemEvents = function(item) {
// Boolean flag for mouseup to know if was drag or click
var dragged;
// For tracking if dragging or clicking is happening
item.on('mousedown', function(e) {
dragged = false;
});
// On click toggle selection
item.on('mouseup', function(event) {
event.stopPropagation(); // Only for item applied to
event.preventDefault();
if(!dragged) {
var justAdded = addIfNotInSelectedItems(item);
if(!justAdded) { // Item was in selection group, remove it
item.remove();
paper.project.activeLayer.addChild(item);
this.selectedColor = paper.project.activeLayer.selectedColor;
//item.selected = false;
}
}
});
// Show as selectable even after has been deselected
item.on('mousemove', function(event) {
this.selected = true;
})
// If not selected, on mouse enter show that it is selectable
item.on('mouseenter', function(event) {
if(!this.selected) {
this.selected = true;
}
});
// If not selected, on mouse leave remove indicator that is selectable
item.on('mouseleave', function(event) {
var isInSelectedItems = selectedItems.getItem(item);
if(this.selected && isInSelectedItems == null) {
this.selected = false;
}
});
// On drag, move item
item.on('mousedrag', function(event) {
dragged = true;
// If user starts dragging automatically select the item
addIfNotInSelectedItems(item);
});
}
var addIfNotInSelectedItems = function(item) {
var isInSelectedItems = selectedItems.getItem(item);
if(isInSelectedItems == null) { // Item not currently in selection group, add it
selectedItems.addChild(item);
item.selectedColor = 'green';
item.selected = true;
return true; // Was added, return true
} else {
return false; // Already in, return false
}
}
var registerCanvasEvents = function() {
if(paper.view != null && canvas != null) {
// Zoom on mousewheel
$(canvas).mousewheel(function(event) {
event.preventDefault();
var mousePosition = new paper.Point(event.offsetX, event.offsetY);
var viewPosition = paper.view.viewToProject(mousePosition);
var returnedValues = panAndZoom.changeZoom(paper.view.zoom, (event.deltaY * -1), paper.view.center, viewPosition, 1.1);
var newZoom = returnedValues[0];
var offset = returnedValues[1];
paper.view.zoom = newZoom;
paper.view.center = paper.view.center.add(offset);
});
// For tracking if dragging or clicking is happening
var dragged;
paper.project.layers[0].on('mousedown', function(e) { // TODO should be layer 0 in long run?
dragged = false;
});
// Pan on mouse drag
/*paper.project.layers[0].on('mousedrag', function(event) { // TODO should be layer 0 in long run?
if(!event.event.ctrlKey && !event.event.altKey && !event.event.shiftKey) { // No keys (that we use) can be pushed
dragged = true; // We're panning, we don't wish to deselect all items as we would do with a click
paper.view.center = panAndZoom.changeCenter(paper.view.center, event.delta.x, event.delta.y, 0.7);
//event.preventDefault();
}
});*/
// Move selected items on mouse drag
selectedItems.on('mousedrag', function(event) {
event.stopPropagation(); // Don't propogate up or it will register as a pan event
event.preventDefault();
dragged = true; // We're panning, we don't wish to deselect all items as we would do with a click
this.translate(new paper.Point(event.delta.x, event.delta.y));
});
// If was a click and not a drag, deselect selected items
paper.project.layers[0].on('mouseup', function(event) {
if(!dragged) {
var removedItems = selectedItems.removeChildren(); // Remove from selection group, which also removes from display
paper.project.activeLayer.addChildren(removedItems); // Return to display
// Reset selection colors for showing selectable
for(var i =0; i < removedItems.length; i++) {
removedItems[i].selectedColor = paper.project.activeLayer.selectedColor;
removedItems[i].selected = false;
}
}
});
// Initial path object, will be reset for new paths after Alt is released
var path = newPath();
var paths = [];
paths.push(path);
// On mousedown add point to start from
paper.project.layers[0].on('mousedown', function(event) {
if(event.event.altKey && !event.event.ctrlKey) { // Alt key to add a path, but disallow attempting to add text at the same time
if(paths[paths.length-1].lastSegment == null) {
//path.add(event.point, event.point);
paths[paths.length-1].add(event.point, event.point);
} else {
//path.add(path.lastSegment.point, path.lastSegment.point);
paths[paths.length-1].add(paths[paths.length-1].lastSegment.point, paths[paths.length-1].lastSegment.point);
}
}
});
// On mousedrag add points to path
paper.project.layers[0].on('mousedrag', function(event) {
if(event.event.altKey && !event.event.ctrlKey) { // Alt key to add a path, but disallow attempting to add text at the same time
if(event.event.shiftKey) { // Use shift key for freeform
//path.add(event.point);
paths[paths.length-1].add(event.point);
} else { // Default of straight line added to path
//path.lastSegment.point = event.point;
paths[paths.length-1].lastSegment.point = event.point;
}
}
}.bind(this));
var tool = new paper.Tool();
var startDragPoint;
// Capture start of drag selection
paper.tool.onMouseDown = function(event) {
if((event.event.ctrlKey && event.event.shiftKey) || (event.event.ctrlKey && event.event.altKey)) {
startDragPoint = new paper.Point(event.point);
}
};
paper.tool.onMouseDrag = function(event) {
// Panning
if(!event.event.ctrlKey && !event.event.altKey && !event.event.shiftKey) { // No keys (that we use) can be pushed
dragged = true; // We're panning, we don't wish to deselect all items as we would do with a click
paper.view.center = panAndZoom.changeCenter(paper.view.center, event.delta.x, event.delta.y, 0.7);
//event.preventDefault();
}
// Show box indicating the area that has been selected
// For moving area and whiting out area
if((event.event.ctrlKey && event.event.shiftKey) || (event.event.ctrlKey && event.event.altKey)) {
dragged = true;
var showSelection = new paper.Path.Rectangle({
from: startDragPoint,
to: event.point,
strokeColor: 'red',
strokeWidth: 1
});
// Stop showing the selected area on drag (new one is created) and up because we're done
showSelection.removeOn({
drag: true,
up: true
});
}
};
// Capture start of drag selection
paper.tool.onMouseUp = function(event) {
if((event.event.ctrlKey && event.event.shiftKey) || (event.event.ctrlKey && event.event.altKey)) {
var endDragPoint = new paper.Point(event.point);
if(event.event.ctrlKey && event.event.shiftKey) { // Whiteout area
whiteoutArea(startDragPoint, endDragPoint);
} else if(event.event.ctrlKey && event.event.altKey) { // Move selected area
selectArea(startDragPoint, endDragPoint);
}
}
};
// Key events
paper.tool.onKeyUp = function(event) {
// Delete selected items on delete key
if(event.key == 'delete') {
selectedItems.removeChildren();
} else if (event.key == 'option') {
registerItemEvents(paths[paths.length-1]);
// Start a new path
paths.push(newPath());
}
}
}
}
// These variables are scoped so that all methods in PaperFunctions can access them
var canvas; // Set by setCanvas
var imageHeight; // Set by setCanvasImage
var raster;
var toolsSetup = false;
var setCanvas = function(canvasElement) {
canvas = canvasElement;
paper.setup(canvas);
};
var setCanvasImage = function(imageObject) {
if(imageObject != null)
{
imageHeight = imageObject.height;
var imageWidth = imageObject.width;
// Set up HTMLImage
var imageElement = new Image(imageObject.width, imageObject.height);
if(_.has(imageObject, 'imageData')) { // Came as 64 bit data
imageElement.src = 'data:image/png;base64,' + imageObject.imageData;
} else if(_.has(imageObject, 'imageUrl')) { // Came as URL
imageElement.src = imageObject.imageUrl;
}
// Add image to Paper.js canvas
imageElement.onload = function(event) {
//canvas.height = $(document).height()-3; // Set canvas height. Why do this here and not in the React component? Because we set the width here too, so we're keeping those together. Perhaps in the future this will be changed when we are responsive to window resizing.
//scalingFactor = canvas.height / imageObject.height; // Determine the ratio
//canvas.width = imageElement.width * scalingFactor; // Scale width based on height; canvas height has been set to the height of the document
// Initialize Paper.js on the canvas
paper.setup(canvas);
raster = new paper.Raster(imageElement, new paper.Point(canvas.width / 2, canvas.height / 2));
//setUpLineAndFreeFormDrawing(); // TODO once we cycle through images will we need to reset this for each new image or can we do this just once?
setUpNotes(); // TODO once we cycle through images will we need to reset this for each new image or can we do this just once?
selectedItems = new paper.Group(); // Since Paper.js has been setup we can now initialize this Group
registerCanvasEvents(); // Panning, zooming, moving selected items, deselecting all selected items
fitToPage();
};
}
};
var fitToPage = function() {
if(paper.view != null && canvas != null) {
// Fit image to page so whole thing is displayed
var scalingFactor = canvas.height / imageHeight; // Constant representation of the ratio of the canvas size to the image size
var zoomFactor = scalingFactor / paper.view.zoom; // Dynamic representation of the zoom needed to return to viewing the whole image in the canvas
// Reset the center point to the center of the canvas
var canvasCenter = new paper.Point(canvas.width/2, canvas.height/2);
paper.view.center = canvasCenter;
// Zoom to fit the whole image in the canvas
var returnedValues = panAndZoom.changeZoom(paper.view.zoom, -1, canvasCenter, canvasCenter, zoomFactor); // Always pass -1 as the delta, not entirely sure why
var newZoom = returnedValues[0];
var offset = returnedValues[1];
paper.view.zoom = newZoom;
paper.view.center = paper.view.center.add(offset);
}
};
var addImage = function(imageDataUrl) {
if(paper.view != null) {
var img = document.createElement("img");
img.src = imageDataUrl;
var presentMomentForId = new Date().getTime() + "-image"; // For purposes of having unique IDs
img.id = presentMomentForId;
img.hidden = true;
document.body.appendChild(img);
var raster = new paper.Raster(presentMomentForId);
registerItemEvents(raster);
}
};
var setUpLineAndFreeFormDrawing = function() {
if(paper.project != null) {
// Initial path object, will be reset for new paths after Alt is released
var path = newPath();
var paths = [];
paths.push(path);
// On mousedown add point to start from
paper.project.layers[0].on('mousedown', function(event) {
if(event.event.altKey && !event.event.ctrlKey) { // Alt key to add a path, but disallow attempting to add text at the same time
if(paths[paths.length-1].lastSegment == null) {
//path.add(event.point, event.point);
paths[paths.length-1].add(event.point, event.point);
} else {
//path.add(path.lastSegment.point, path.lastSegment.point);
paths[paths.length-1].add(paths[paths.length-1].lastSegment.point, paths[paths.length-1].lastSegment.point);
}
}
});
// On mousedrag add points to path
paper.project.layers[0].on('mousedrag', function(event) {
if(event.event.altKey && !event.event.ctrlKey) { // Alt key to add a path, but disallow attempting to add text at the same time
if(event.event.shiftKey) { // Use shift key for freeform
//path.add(event.point);
paths[paths.length-1].add(event.point);
} else { // Default of straight line added to path
//path.lastSegment.point = event.point;
paths[paths.length-1].lastSegment.point = event.point;
}
}
}.bind(this));
// Each time Alt comes up, start a new path
paper.tool.onKeyUp = function(event) {
if(event.key == "option") {
registerItemEvents(paths[paths.length-1]);
// Start a new path
paths.push(newPath());
}
};
}
};
// Establishes default line style
var newPath = function() {
var path = new paper.Path();
path.strokeColor = 'black';
path.strokeWidth = 10;
return path;
};
var note = "";
var setNote = function(newNote) {
note = newNote;
};
var setUpNotes = function() {
if(paper.project != null) {
paper.project.layers[0].on('mousedown', function(event) { // TODO should be layer 0 in long run?
if(event.event.ctrlKey && !event.event.altKey && !event.event.shiftKey) { // Only Ctrl key to add text
// Add text box
var textBox = new paper.PointText(event.point);
textBox.justification = 'left';
textBox.fillColor = 'black';
textBox.fontSize = 60;
textBox.content = note;
registerItemEvents(textBox);
}
});
}
};
var selectArea = function(startDragPoint, endDragPoint) {
var rasterTopLeftCorner = new paper.Point(raster.bounds.topLeft);
var adjustedStartDragPoint = new paper.Point(startDragPoint.x - rasterTopLeftCorner.x, startDragPoint.y - rasterTopLeftCorner.y);
var adjustedEndDragPoint = new paper.Point(endDragPoint.x - rasterTopLeftCorner.x, endDragPoint.y - rasterTopLeftCorner.y);
var boundingRectangleRasterCoordinates = new paper.Rectangle(adjustedStartDragPoint, adjustedEndDragPoint);
var boundingRectangleCanvasCoordinates = new paper.Rectangle(startDragPoint, endDragPoint);
var selectedArea = raster.getSubRaster(boundingRectangleRasterCoordinates);
var whitedOutSelection = new paper.Shape.Rectangle(boundingRectangleCanvasCoordinates);
whitedOutSelection.fillColor = 'white';
whitedOutSelection.insertAbove(raster); // Whiteout just above the image we're working with
registerItemEvents(selectedArea);
}
var whiteoutArea = function(startDragPoint, endDragPoint) {
var whitedOutSelection = new paper.Shape.Rectangle(startDragPoint, endDragPoint);
whitedOutSelection.fillColor = 'white';
whitedOutSelection.insertAbove(raster); // Whiteout just above the image we're working with
}
var flattenToDataUrl = function() {
layerAsRaster = paper.project.layers[0].rasterize(); // TODO should be layer 0 in long run? // Layer to Paper.js Raster object
layerAsRaster.visible = false;
var dataString = layerAsRaster.toDataURL();
return dataString;
};
module.exports = {
setCanvas: setCanvas,
setCanvasImage: setCanvasImage,
fitToPage: fitToPage,
addImage: addImage,
setNote: setNote,
flattenToDataUrl: flattenToDataUrl
};
Additionally, here's the SimplePanAndZoom.js file for clarity. It uses minimal Paper functions, it mainly just does calculations:
// Based on http://matthiasberth.com/articles/stable-zoom-and-pan-in-paperjs/
var SimplePanAndZoom = (function() {
function SimplePanAndZoom() { }
SimplePanAndZoom.prototype.changeZoom = function(oldZoom, delta, centerPoint, offsetPoint, zoomFactor) {
var newZoom = oldZoom;
if (delta < 0) {
newZoom = oldZoom * zoomFactor;
}
if (delta > 0) {
newZoom = oldZoom / zoomFactor;
}
// Zoom towards offsetPoint, not centerPoint (unless they're the same)
var a = null;
if(!centerPoint.equals(offsetPoint)) {
var scalingFactor = oldZoom / newZoom;
var difference = offsetPoint.subtract(centerPoint);
a = offsetPoint.subtract(difference.multiply(scalingFactor)).subtract(centerPoint);
}
return [newZoom, a];
};
SimplePanAndZoom.prototype.changeCenter = function(oldCenter, deltaX, deltaY, factor) {
var offset;
offset = new paper.Point(-deltaX, -deltaY);
offset = offset.multiply(factor);
return oldCenter.add(offset);
};
return SimplePanAndZoom;
})();
module.exports = SimplePanAndZoom;
Thanks.
I'm taking some guesses here but I'll address some problems in the code that will hopefully address the behavior you're seeing.
First, I presume paper.project.layers[0] is paper.project.activeLayer. Once that has been rasterized 1) the raster is added to the layer and setting visible = false does cause it to disappear when an update is done.
Second, when you invoke paper.setup(canvas) in imageElement.onload you create a new paper project. This project starts out as the active project and makes the previous project "disappear". So when you create a raster with raster = new paper.Raster(...) it goes into the new project, not the old project.
So now there is a hidden (.visible = false) raster in the old project (let's call it project1) and a new version of it in project2.
I'm not sure if this is the intended behavior or not, but when you invoke paper.setup(canvas) for what seems to be the second time then paper seems to notice that they both refer to the same canvas and keeps project1 and project2 in sync. So creating the second project clears the first project's children array. And adding new paper.Raster(...) ends up adding the raster to project1 and project2.
Now I can't tell what the next piece of the puzzle is. You'd need to add some information like 1) where the mouse event handlers are setup and what they are attached to, 2) what setUpNotes() does, 3) what registerCanvasEvents() does, and 4) what fitToPage does.
There are a few globals created, imageHeight and raster that probably aren't intentional. And it's not clear why you need to use new Image() at all - paper.Raster() accepts URLs, including data URLs.
I was surprised paper cleared the first project. It's curious.
Version 2:
Let me take a stab at structuring this using layers. I'd suggest you get rid of multiple projects because having mouse event handlers attached to multiple projects that share the same canvas adds too much complexity.
So, in your code initialization: paper.setup(canvas). Do this once and only once.
Setup the initial image in the single layer initially created by paper.
// this will be inserted into the current layer, project.activeLayer
var raster = new paper.Raster(imageURL, paper.view.bounds.center);
When the image in your queue changes do something like:
// make the existing image/layer invisible
paper.project.activeLayer.visible = false;
// add a new layer which is inserted in the project and activated
var layer = new paper.Layer();
// the new layer is activated, create a raster for the image
var raster = new paper.Raster(imageURL, paper.view.bounds.center);
// now do your normal logic for editing, zooming, etc.
It's really a bit more complicated than that because you have a queue of images and you only want to create a layer the first time you visit an image. You could initialize all the rasters at the outset, something like:
var imageURLs = ["url to image1", "url to image2", "etc"];
imageURLs.forEach(function(url) {
new paper.Layer();
paper.project.activeLayer.visible = false;
new paper.Raster(url, paper.view.bounds.center);
});
// make the first layer visible and activate it
paper.project.layers[0].visible = true;
paper.project.layers[0].activate();
The preceeding code gives you a parallel array to the images in your queue so switching images is straightforward - there is no checking to see if that image has been created or not:
function setImage(index) {
paper.project.activeLayer.visible = false;
paper.project.layers[index].activate();
paper.project.layers[index].visible = true;
}
Finally, I would make sure my mouse handling wasn't causing me problems. From the new code you posted it looks like each project had a global tool that handled 'mousedown', 'mousedrag', and 'mouseup' events, another set of handlers for activeLayer for 'mousedown', 'mousedrag', and 'mouseup' events, and also selectedItems has a handler for 'mousedrag'. I can't keep track of what all the different handlers are supposed to do across projects. I'm guessing that these are the root issue with the flickering you saw.
I would likely just use paper.view.on for 'mousedown', 'mousedrag', and 'mouseup' events. When I get an event I would check to see if anything on the layer was hit by using the following:
paper.project.activeLayer.hitTest(event.point);
Being able to set events on the view is new for paper but very useful. There may be a few other tweaks necessary to handle highlighting unselected items. A relatively straightforward way to handle that is to have a group of selected items and a group of unselected items:
unSelectedGroup.on('mouseenter', function() {
unSelectedGroup.selected = true;
});
unSelectedGroup.on('mouseleave', function() {
unSelectedGroup.selected = false;
});
These should be safe across layers when only one layer is visible at a time. I would set up these group handlers when setting up the images, whether all up front or on an as-needed basis. Alternatively, you could also add paper.view.on('mousemove', ...) and handle the 'mouseenter' and 'mouseleave' events yourself using hitTest as shown above, but either approach should work.
I think using a layer-based approach to your images will keep things in sync. There are enough problems with the project-based approach and many different mouse event handlers that you'll be on more stable ground regardless.

Unable to clear the canvas

I don't know why, but the clearRect() does not work.
This is a function that is executed every time I click on a panel or every time I change the thickness' value.
//When click on a menu section
$(".menuSection").click(function() {
//Show hide the selected item
$(this).next().toggle();
//hide all the other panels
$(this).next().siblings(".panel").hide();
//To update the values in the colors panel when selected
if ( $(this).prop("id") == "colors" ) {
changeColorBySliders();
}
if ( $(this).prop("id") == "pen" ) {
updatePreview();
}
});
//when thickness slider change:
$("#penPanel input[type=range]").on("input", updatePreview);
The fact is that it draws the line, but if I click it again it's doesn't reset.
var $preview = $("#preview");
var contextPreview = $preview[0].getContext("2d");
//Function to update the pen's preview
function updatePreview() {
console.log($("#thickness").val());
var rgba = $("#mainCanvas").css("background-color");
$("#preview").css("background-color", rgba);
//Resetting the preview
contextPreview.clearRect(0, 0, $preview.width, $preview.height);
//Drawing an example path
contextPreview.beginPath();
contextPreview.moveTo(50, 30);
contextPreview.lineTo(100, 110);
contextPreview.quadraticCurveTo(115, 120, 125, 80);
contextPreview.bezierCurveTo(145, -40, 150, 120, 200, 95);
contextPreview.lineTo(250, 65);
contextPreview.lineWidth = $("#thickness").val();
contextPreview.strokeStyle = color;
contextPreview.stroke();
contextPreview.closePath();
}
Any help?
Solution
I solved the problem using this kind of declaration:
var preview = document.getElementById("preview");
var contextPreview = preview.getContext("2d");
contextPreview.clearRect(0, 0, preview.width, preview.height);
Insted of the jquery one:
var $preview = $("#preview");
var contextPreview = $preview[0].getContext("2d");
Why?
it's because $preview is a jQuery object, $preview.width is therefore a function, so when you called clearRect(), you were actually calling contextPreview.clearRect(0,0, function, function) so your rect dimensions were undefined or 0 so it wasn't clearing a single pixel.
So you can still use jQuery but be sure you call contextPreview.clearRect(0,0, $preview[0].width, $preview[0].height)
var preview = document.getElementById("preview");
var contextPreview = preview.getContext("2d");
contextPreview.clearRect(0,0, $preview[0].width, $preview[0].height)
Special Thanks to Kaiido.

CreateJS Tween on keyDown

I ahave a problem implementing TweenJS on keydown. It only tweens once and after that if I press key there is no another tween.
What I have so far is:
var rotate = false;
document.onkeydown = keyDown;
document.onkeyup = keyUp;
function keyDown(e) {
switch(e.keyCode) {
case 32:
if(!rotate) {
rotate = true;
var t = createjs.Tween.get(rect).to({rotation:360},450, createjs.Ease.BackInOut).call(function(){
rotate = false;
});
}
break;
}
}
As I said, if I hit space, the rectangle rotates just as I want but after it finished rotation var rotate is set back to false as I wanted and after another press on space there is no another rotation.
So, my question is How to tween some element on click or keyDown?
This is because you have already rotated the rect to 360, so rotating it again does nothing (it is already at its target).
An easy solution is to toss in a zero-duration to() call before or after the main rotation, which resets the rotation value so it can be tweened again.
createjs.Tween.get(rect)
.to({rotation:0}) // THIS ONE
.to({rotation:360}, 450, createjs.Ease.BackInOut)
.call(function(){
rotate = false;
// You could also reset it here:
// rect.rotation = 0;
});

Event Handling Javascript

in a map I want when the user clicks inside the map to be able to draw with his mouse a scheme. For example it clicks and then circles an area just by moving his mouse. The problem is that when he circles the area, continues to draw at the current mouse position.
In other words I want the user to click for start drawing and click again to stop it.
I am using addEventListener and removeEventListener
I am trying to remove the events from the map but it does not work.
Any ideas?
Code:
map.addEventListener('click', goInter, false);
function goInter() {
map.addEventListener('mousemove', move, false);
map.addEventListener('click', close, false);
var pointList = [];
var first_element;
var trig = 0;
function move(e) {
map.dragging.disable();
pointList[pointList.length] = new L.LatLng(e.latlng.lat, e.latlng.lng);
first_element = pointList[0];
//ama to valw den doulebei tipota!!
//document.getElementById("elements").innerHTML = pointList[ii++];
if (pointList.length > 400){
pointList = [];
}
var line = new L.Polyline(pointList, {
color: 'red',
weight: 2,
opacity: 0.5,
});
map.addLayer(line);
if (trig == 1){
map.preventDefault();
alert("den einai 1");
return false;
}
};
function close(){
//map.removeEventListener ('mousemove', move, false);
var last_points = [first_element, pointList[pointList.length-1]];
var last_connection = new L.Polyline(last_points, {
color: 'blue',
weight: 1,
opacity: 0.9
});
map.addLayer(last_connection);
trig = 1;
map.preventDefault();
//map.removeLayer(line);
//map.fitBounds(line.getBounds());
};
};
I have a progress -> i changed the two click events to -> mouseup and mousedown respectively. That gives me a better interaction. when the user releases the button it stops drawing. However if you press it again it draws. ALSO uncomment first line of close() function

How to update text when using mouseMoveMethod?

I'm new to programming and take Javascript as a school course. I have come upon this problem, and have been stuck because I have been unable to update the text; for instance, when I move my mouse over the canvas, it just overlaps the text. Is there any solution to updating text, or am I just missing something basic?
/* This program displays the x and y
* coordinates in a label on the screen
* and updates when the mouse moves */
function start(){
mouseMoveMethod(drawCoordinates);
}
function drawCoordinates(e){
var txt = new Text(e.getX(), "15pt Arial");
var text = new Text(e.getY(), "15pt Arial");
txt.setPosition(100, 100);
txt.setColor(Color.black);
add(txt);
text.setPosition(100, 200);
text.setColor(Color.black);
add(text);
}
The problem is that you're creating a new Text every time the drawCoordinates method executes.
If this was browser based, you'd need something like this...
function drawCoordinates(e){
//Check if we can find the lable for X first.
//If we can't, create a new one....
var txt = document.getElementById('txtX');
if(txt==null)
{
txt = new Text(e.getX(), "15pt Arial");
txt.setPosition(100, 100);
txt.setColor(Color.black);
add(txt);
}
else
txt.text = e.getX();
//and the same for Y
}
Hope that helps

Categories

Resources