Incorporate the paper.js library seamlessly within an Angular.js project

I'm currently facing an issue with integrating paper.js into angular.js. The main problem I am encountering is determining where to load the paperscript part.

Within my project, I have a view and a controller, but I am unsure of where to place the code. It seems that placing it in the controller doesn't work, and putting it in the view causes it not to load.

This is what my controller looks like:

    var hash = window.location.hash.split('/');

$scope.status = 'Loading';
var request = jQuery.ajax(system.server, {
    'url': system.server,
    'headers': {
        'Accept': 'application/json',
        'Request': system.request + '/hcbs/allocations/resident/' + hash[3],
        'Username': system.username,
        'Password': system.password
    }
})
.always(function(response)
{
    signature.constructor();
    switch(response.status)
    {
        case 200:
        case undefined:
            $scope.$apply(function()
            {
                $scope.status = '';
                var res = JSON.parse(response);
                $scope.hcbsAllocations = res.hcbsServiceAllocations;

                $scope.change = function(allocationId)
                {
                    console.log(jQuery('[data='+ allocationId +'][name=startDate]').val());
                    console.log(jQuery('[data='+ allocationId +'][name=endDate]').val());
                }

                $scope.submit = function(allocationId)
                {
                    // Validate dates

                    // Make signature popup
                    $scope.signaturePop = true;
                }
            });
            break;
        case 404:
            console.log('error ' + response.status);
            $scope.$apply(function()
            {
                $scope.status = 'Problems loading resource at the moment';
            });
        default:
            console.log(response);
    }
});

Here's how my view is structured:

<div id="app-content">
    <div consumer />

    <h1>Consumer</h1>

    <div ng-show="status">
        <div class="notice">
            <p>{{status}}</p>
        </div>
    </div>

    <form name="attendance">
        <table class="hcbs">
            <tr ng-repeat="allocation in hcbsAllocations">
                <td class="first"><h3>{{allocation.type}}</h3></td>
                <td class="middle">
                        <input type="datetime-local" name="startDate" ng-model="startDate" ng-change="change(allocation.id)" data="{{allocation.id}}" placeholder="Choose start date" />

                        <input type="datetime-local" name="endDate" ng-model="endDate" ng-change="change(allocation.id)" data="{{allocation.id}}" placeholder="Choose end date" />
                </td>
                <td class="last">
                    <span class="btn" class="submit" data="{{allocation.id}}" ng-click="submit(allocation.id)"><i class="icon-ok icon-large"></i></span>
                </td>    
            </tr>
        </table>
    </form>
</div>

Answer №1

Here is the directive approach for drawing using HTML canvas:

Take a look at the example on jsFiddle

HTML:

<canvas id="canvas" resize draw></canvas>

Directive code:

app.directive('draw', function () {
    return {
        restrict: 'A',
        link: function postLink(scope, element, attrs) {
            var path;
            var drag = false;

            function mouseUp(event) {
                //Clear Mouse Drag Flag
                drag = false;
            }

            function mouseDrag(event) {
                if (drag) {
                    path.add(new paper.Point(event.layerX, event.layerY));
                    path.smooth();
                }
            }

            function mouseDown(event) {
                //Set flag to detect mouse drag
                drag = true;
                path = new paper.Path();
                path.strokeColor = 'black';
                path.add(new paper.Point(event.layerX, event.layerY));
            }

            function initPaper() {
                paper.install(window);
                paper.setup('canvas');
            }

            element.on('mousedown', mouseDown).on('mouseup', mouseUp).on('mousemove', mouseDrag);

            initPaper();

        }
    };
});

Answer №2

If you want to use JavaScript directly instead of loading paperscript, you can do so easily.

<body ng-controller="PaperController">

    <canvas id="canvas" resize ng-mousedown="mouseDown($event)" ng-mousemove="mouseDrag($event)" ng-mouseup="mouseUp()"></canvas>
</body>
<script type="text/javascript>
function PaperController($scope){

    var path;
    var drag = false;

    $scope.mouseUp = function(){
        //Clear Mouse Drag Flag
        drag = false;
    };

    $scope.mouseDrag = function(event){
        if(drag){
            path.add(new paper.Point(event.x, event.y));
            path.smooth();
        }
    };

    $scope.mouseDown = function(event){
        //Set flag to detect mouse drag
        drag = true;
        path = new paper.Path();
        path.strokeColor = 'black';
        path.add(new paper.Point(event.x, event.y));
    };

    init();
    function init(){
        paper.install(window);
        paper.setup('canvas');
    }
}

</script>

Answer №3

I have encountered issues with the previous solutions provided, as they contain excess code and unnecessary IDs.

Check out my jsFiddle link

For example, let's say I only have a simple element like this:

<canvas draw></canvas>

Here is an uncomplicated directive that could be used with the above element:

app.directive('draw', function () {
    return {
        restrict: 'A',
        link: function (scope, element, attrs) {
            var path;
            paper.setup(element.get(0));
            var tool = new paper.Tool();
            tool.onMouseDown = function (event) {
                path = new paper.Path();
                path.strokeColor = 'black';
            };
            tool.onMouseDrag = function (event) {
                path.add(event.point);
            };
            tool.onMouseUp = function (event) {
                //no specific actions needed here
            };
        }
    };
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is there a bug hiding in the Angular code for the Codecademy Calendar App waiting to be found?

Currently, I am working on the Codecademy task - CalendarApp utilizing AngularJS which involves services and routing. Unfortunately, it seems to have some issues as the data is not displaying correctly and the expression: {{ day.date | date }} appears as i ...

if statement based on the conditions set in the CSS

I've been struggling with an issue for a whole day now, and I just can't seem to solve it. I have a few keydown functions that change the background image under certain conditions when the 'active' class is not present. Here's an e ...

Issues with JQuery and Bootstrap Button not working properly inside a Popover

I am currently facing some challenges while attempting to execute an AJAX call within a bootstrap pop-over. PHP: $my-data-content = '<div><form> <select class="form-control"> <option value="Enable">Enable</option> <o ...

JavaScript layout: Thymealf

I have a unique thymeleaf template like so: <body> <div id="layout"> <!-- Menu toggle --> <a href="#menu" id="menuLink" class="menu-link"> <!-- Hamburger icon --> <span>& ...

What is the best way to connect methods using variables?

const people = { person1: { first: "Yassine", last: "Boutabia", }, person2: { first: "Md Jahidul Hasan", last: "Mozumder", }, person3: { first: "Md Feroj", last: "Ahmod", }, } retrieveInfo = () => { var prop ...

What is the most effective method for updating a className in Next.js using CSS Modules when a button is activated?

Looking to create a responsive navigation bar that transforms based on screen size? When the width reaches 600px, I'd like to hide the links and instead show a clickable nav button that reveals those options. Upon inspecting my list elements in the c ...

AngularJS radio buttons are unable to be selected in a simplistic manner

I have implemented a dynamic list display using HTML radio buttons. Here is the code snippet: <html> <head> <script src="angular-v1.5.5.js"></script> </head> <body> <div ng-app="myApp" ng-controller=" ...

Using Nested ng-repeat for Values and Keys in Angular

Struggling with implementing nested ng-repeats in my code. I have a JSON object with multiple layers and attempting to iterate through them to display the data. Here is the structure of the JSON: { "status": "success", "data": { "Mat": { "tota ...

Custom server-side methods in SignalR

Not long ago, I was puzzled as to why clients were not triggering any server-side code. No one had an answer, but after some more investigation, I discovered that the clients do actually get registered on the server. When I override the onConnect method on ...

Parsing dates using moment.js with strict format and specific locale

In a scenario, I face the challenge of dealing with dates in different locales and trying to parse them into RFC2822. However, there seems to be an issue where moment.js fails to parse certain dates correctly. For instance, the date "24 janv. 2022" does n ...

Avoiding unlimited re-renders when using useEffect() in React - Tips and Strategies

As a new developer, I recently built a chat application using socket io. In my code, I have the useEffect hook set to only change when the socket changes. However, I also have setMessage within the body of useEffect(), with socket as a dependency. Unfortun ...

Building with bricks and mortar does not involve organizing visual content

I'm currently trying to organize some fairly large images using masonry, but the code below doesn't seem to be working. I'm using node.js with express and have installed the masonryjs package in an attempt to make it work, but that approach ...

Attempting to utilize JSON.Stringify on Scripting.Dictionary objects will result in failure

In my current ASP classic project, I have integrated the JScript JSON class available at this link. This class can interact with both VBScript and JScript, closely resembling the code provided on json.org. However, due to team manager's requirement, I ...

Transforming a canvas into a div element

Hey there, I'm looking to swap out one canvas for another but I'm not sure how it will look on the browser. Any help would be greatly appreciated. <div id="juego"> <canvas width="203" height="256" id="1" class="bloque"></canvas& ...

Use JavaScript to send GET parameters to the server without needing to refresh the page

My goal is to execute a GET request in JavaScript when a download link is clicked. Upon clicking the link, a GET request should be sent to a PHP script that tracks the number of times the link is clicked. Although I'm relatively new to JavaScript, I h ...

Utilizing TypeScript generics to accurately extract type information from state during reduction

In the context of a state reducer presented as follows: const anObject = { fruit: 'Apple', today: new Date(), } function reducer(state, stateReducer) { return stateReducer(state); } const fruit = reducer(anObject, state => state.fruit ...

Showing button based on a particular value

I am trying to dynamically display a button based on the value of the sendSMS property for the logged-in user. I have added this property in the viewer model, which is connected to the user's base model. However, I am encountering difficulties with us ...

What is the best way to send only one variable from a complex JavaScript file?

index.js $(window).resize(function(){ var page = location.pathname.split('/').slice(-1)[0]; if (page != "minw.php") {goback = location.pathname;} var w1 = document.documentElement.clientWidth; var minw = 800; if (w1 < minw ...

Creating a 2D array of multiplication tables using JavaScript

My current task involves creating a program that generates a multiplication table for a given variable 'n'. The results must be stored in a two-dimensional array and displayed in the console with proper data formatting. Although I am familiar wit ...

Using node.js to set the billing address while confirming a Stripe Payment intent

Is there a way to specify the billing address of a payment intent with Node.js? When using the Stripe.js browser-side framework, I can easily accomplish this by utilizing Stripe elements and the stripe.confirmPayment function, which automatically captures ...