Modifying canvas border colors using AngularJS

Currently, I am in the process of learning AngularJS and have developed a website that includes a canvas element. My main objective is to change the border color after clicking on a checkbox.

Here is the code snippet for canvas.html :

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Canvas</title>
    <link rel="stylesheet" type="text/css" href="/canvas/canvas.css">
</head>

<body ng-app="ngAnimate">

    <canvas id="myCanvas" width="1200" height="800"></canvas>
    <script src="/canvas/canvas.js"></script>

    <h1>Change color: <input type="checkbox" ng-model="checkBox"></h1>

    <div ng-canvasGreen="checkBox"></div>

    <script src="/scripts/angular.min.js"></script>
    <script src="/scripts/angular-animate.js"></script>

</body>
</html>

The code for canvas.js:

// Global variables
var canvas, ctx, mousePos, mouseButton;

window.onload = function init() {
    
    // Get the canvas element
    canvas = document.querySelector("#myCanvas");

   
    w = canvas.width;
    h = canvas.height;
    scale = w / 150;

    // Get the drawing context
    ctx = canvas.getContext('2d');

    // Filled rectangle
    ctx.fillStyle = 'red';
    ctx.fillRect(10 * scale, 10 * scale, 30 * scale, 30 * scale);

    // Wireframe rectangle
    ctx.strokeStyle = 'green';
    ctx.lineWidth = 4 * scale;
    ctx.strokeRect(100 * scale, 40 * scale, 40 * scale, 40 * scale);
    ctx.fillStyle = 'yellow';
    ctx.fillRect(100 * scale, 40 * scale, 40 * scale, 40 * scale);

    // Fill circle
    ctx.beginPath();
    ctx.arc(60 * scale, 60 * scale, 10 * scale, 0 * scale, 2 * scale * Math.PI);
    ctx.fill();

    // Text
    ctx.fillStyle = "purple";
    ctx.font = 20 * scale + "px Arial";
    ctx.fillText("Hello!", 60 * scale, 20 * scale);

    canvas.addEventListener('mousemove', function (evt) {
        mousePos = getMousePos(canvas, evt);
        var message = 'Mouse position: ' + Math.round(mousePos.x, 0) + ',' + Math.round(mousePos.y,0);
        writeMessage(canvas, message);
    }, false);

    canvas.addEventListener('mousedown', function (evt) {
        mouseButton = evt.button;
        var message = "Mouse button " + evt.button + " down at position: " + Math.round(mousePos.x,0) + ',' + Math.round(mousePos.y,0);
        writeMessage(canvas, message);
    }, false);

    canvas.addEventListener('mouseup', function (evt) {
        var message = "Mouse up at position: " + Math.round(mousePos.x,0) + ',' + Math.round(mousePos.y,0);
        writeMessage(canvas, message);
    }, false);
}

function writeMessage(canvas, message) {
    ctx.save();
    ctx.clearRect(0, 0, 600, 50);
    ctx.font = '18pt Calibri';
    ctx.fillStyle = 'black';
    ctx.fillText(message, 10, 25);
    ctx.restore();
}

function getMousePos(canvas, evt) {
    var rect = canvas.getBoundingClientRect();
    return {
        x: evt.clientX - rect.left,
        y: evt.clientY - rect.top
    };
}

The content for canvas.css:

canvas {
   transition: all linear 1.5s;
   border: 1px solid black;
   border-width: 15px;
}

.ng-canvasGreen {
   border: 1px solid green;
   border-width: 15px;
}

I encountered an issue where clicking on the checkbox does not trigger any changes, and the border color remains unchanged.

Answer №1

Check out the code snippet below:

var app = angular.module('ngAnimate', []);
app.controller('myCtrl', function($scope) {
$scope.changeborder = function(event){
  if(event.target.checked == true){
    $("canvas").css("border-color","red");
  }
  if(event.target.checked == false){
    $("canvas").css("border-color","yellow");
  }
}
// Global variables for canvas
var canvas, ctx, mousePos, mouseButton;

window.onload = function init() {
    // called AFTER the page has been loaded
    canvas = document.querySelector("#myCanvas");

    w = canvas.width;
    h = canvas.height;
    scale = w / 150;

    ctx = canvas.getContext('2d');

    // Draw a filled rectangle
    ctx.fillStyle = 'red';
    ctx.fillRect(10 * scale, 10 * scale, 30 * scale, 30 * scale);

    // Draw a wireframe rectangle
    ctx.strokeStyle = 'green';
    ctx.lineWidth = 4 * scale;
    ctx.strokeRect(100 * scale, 40 * scale, 40 * scale, 40 * scale);
    ctx.fillStyle = 'yellow';
    ctx.fillRect(100 * scale, 40 * scale, 40 * scale, 40 * scale);

    // Draw a fill circle
    ctx.beginPath();
    ctx.arc(60 * scale, 60 * scale, 10 * scale, 0 * scale, 2 * scale * Math.PI);
    ctx.fill();

    // Add text
    ctx.fillStyle = "purple";
    ctx.font = 20 * scale + "px Arial";
    ctx.fillText("Hello!", 60 * scale, 20 * scale);
    }
    });
canvas {
   transition: all linear 1.5s;
   border: 1px solid black;
   border-width: 15px;
}

.ng-canvasGreen {
   border: 1px solid green;
   border-width: 15px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Canvas</title>
    <link rel="stylesheet" type="text/css" href="/canvas/canvas.css">
</head>

<body ng-app="ngAnimate" ng-controller="myCtrl">

    <canvas id="myCanvas" width="1200" height="800"></canvas>
    <script src="/canvas/canvas.js"></script>

    <h1>Change color: <input type="checkbox" ng-click="changeborder($event)" ng-model="checkBox"></h1>

    <div ng-canvasGreen="checkBox"></div>

    <script src="/scripts/angular.min.js"></script>
    <script src="/scripts/angular-animate.js"></script>

</body>
</html>

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

What is the best way to ensure that posts made with Contentlayer stay dynamic for future posts on Vercel?

My issue is that on the webpage I have set up using contentlayer, I display my blog posts from GitHub through Vercel. However, when I publish a new post on GitHub, I am unable to see it because it has not been built yet. What can I do on the Nextjs13 site ...

Tips for designing a sleek and seamless floating button

I attempted to implement a floating button feature that remains in view while smoothly flowing using jQuery. I followed a tutorial I found online to create this for my website. The tutorial can be accessed at this link. However, after following all the ste ...

When an AJAX call is made during a PHP session that has timed out

I am working on an AJAX form that handles data authentication. In the event of a session timeout, I need to implement a redirect to the login page. How can I go about achieving this? Here is an excerpt from my simplified server-side code: function doExecu ...

Tips for managing React state when dealing with multiple axios callbacks that modify an array's state

I am currently working on a React component that allows users to upload images. In this scenario, I aim to upload 3 images. After each file is uploaded, I want to append it to the list of uploaded files. Issue: The setter method in useState is asynchronou ...

Making an HTTP POST request in AngularJS

Upon sending a POST request with headers specified as content-type: application/JSON, the cookie is not being set in the Request Headers. However, when I modify the headers to be content-type: application/x-www-form-urlencoded, the cookie is successfully ...

Looking for ways to incorporate both external and internal styling using jQuery and CSS in my template?

I've been working on a django project for a while now, and I'm facing some challenges with getting external and internal CSS to work. Only inline CSS seems to be functioning properly. I have two questions: How can I get external or internal C ...

Dynamically change the state based on intricate layers of objects and arrays

Here is the issue I am facing I am attempting to update the state of an object named singleCarers I have the index of the roster in the rosters array that I need to update However, the key monday: needs to be dynamic, as well as the keys start: and fini ...

Stay tuned for updates on elements being loaded into a div from an external source

I have a project in progress that involves integrating HTML and JQuery. One of the tasks is to replace a div with a new one from an external HTML file using the load('some.html #someDiv') method. Everything was going smoothly until I tried to li ...

Ways to rearrange an object with javascript

I am looking to restructure my object by removing a nesting. How can I achieve this using JavaScript? Actual: var a = [ { clickedEvents: { 'event-element': 'a', 'event-description': & ...

How to Use Absolute Positioning in Bootstrap 3.0 to Position Child Divs

I have a div block that needs to always be displayed at the bottom of the section, regardless of whether the section above is empty. The inner div should stay at the bottom of the section, as shown in the attached image. This is my current code: <div ...

What are the distinctions between manually and programmatically changing URLs in Angular 6?

My query pertains to differentiating navigation methods, specifically between clicking a button with [routerLink] and manually entering a URL in the browser's search bar. Update: I have a fixed menu on a certain page that appears as follows: <ul& ...

Image not showing up on HTML page following navigation integration

Having trouble with my responsive website setup - the background image for ".hero-image" isn't showing up after adding the navigation. Google Chrome console is throwing a "Failed to load resource: the server responded with a status of 404 (Not Found)" ...

Achieving full white space utilization with inline block elements

When attempting to stack elements on top of each other, I encounter unwanted white space due to varying heights of the elements. I am trying to figure out how to move boxes 6 and 7 up while keeping all corresponding elements beneath them aligned properly. ...

What is the best way to add borders to the cities on interactive SVG maps?

I'm currently developing Interactive SVG Maps showcasing Turkey. The map consists of 81 cities, each represented by <g> elements, and their respective districts, created as child elements within the city elements. It's worth noting that the ...

Using Promise to manipulate objects and arrays returned from functions

https://i.stack.imgur.com/jvFzC.png router.get('/', function (req, res, next) { var size = req.params.size ? parseInt(req.params.size) : 20; var page = req.params.page ? req.params.page>0 ? (size&(parseInt(req.params.page)-1)) : ...

Module not found in Node.js environment (webpack)

I seem to be encountering an issue with loading any modules. Despite reinstalling my operating system, I continue to face the same error when attempting to use any module. I have tried reinstalling node, clearing the cache, and more. To view the code, pl ...

Develop a monitor for an entity that has not been created

Currently, I am tackling a feature that involves tracking an asynchronous request within a synchronous one. Let me elaborate. The code snippet I am working with looks something like this: const myObj = {}; function sendMessage(requestId, data) { kafkaP ...

Resolver for nested TypeORM Apollo queries

I've set up a schema that includes database tables and entity classes as shown below: type User { id: Int! phoneNumber: String! } type Event { id: Int! host: User } Now, I'm attempting to create a query using Apollo like this ...

JSONP OpenWeather API

I've been trying to access and retrieve weather data from OpenWeather using their API, but unfortunately, I'm facing some difficulties in getting it to work. It seems like there might be an issue with the way I am fetching the JSON data. To quer ...

The battle between CSS and jQuery: A guide to creating a dynamic zebra-style table without relying on additional plugins

Is there a better way to create a dynamic zebra styling for table rows while still being able to hide certain elements without losing the styling? In this code snippet, I'm using the CSS :nth-of-type(even) to style even rows but running into issues wh ...