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

The jQuery document.ready event fails to trigger when invoked after using ScriptManager.RegisterStartupScript in the code-behind

I am currently working with a filtered list of items utilizing a tool called Check out the screen for a visual example. In the user flow, after selecting to add another action, a fancybox popup is triggered displaying the next image: After the user adds ...

The footer should always be anchored at the bottom of the webpage, maintaining a consistent position regardless of any changes to the browser's

I've successfully implemented a footer with several buttons that remains positioned at the bottom of the page, 60px above the very bottom, regardless of the content or window size. The CSS I'm using is as follows: #container { min-height: 10 ...

Setting the height of a box-inner div to full height in Bootstrap 4: A guide

Assistance Needed: I have encountered an issue with my design while using bootstrap-4. The box-inner div works perfectly on desktop, adjusting its height according to the content entered. However, on a real iPad, the columns are not of equal height as sho ...

Is it possible to display a variety of color schemes in just one console.log()?

My task involves working with an array of hexadecimal values, "colors": ["#d5dd90","#e6bb45","#ef9770"] To log these out in different colors, I used the following method: colors.forEach((value)=>{ console.log(& ...

Setting up Express routes in a separate file from the main one: a step-by-step

My goal is to organize my routes separately from the main app.js file using the following file structure. I attempted to create a api/user/ post API but encountered a 404 error. Any suggestions on how to resolve this issue with the given file structure? . ...

Please refrain from submitting the form until the slow AJAX jQuery process has finished

My form is experiencing a delay of almost 4 seconds due to the Ajax jQuery I am using, which creates fields within the form. This delay causes some users to submit the form before the necessary fields are created. I need a way to prevent the form from bein ...

I must pause for a specified period before initializing the subsequent component in React Native

Due to restrictions on my API key, I can only make one request every 5 seconds. Therefore, I need to wait for 5 seconds before making another request for NearbyJobs (with the first request being made for PopularJobs). <ScrollView showsVerticalScrollIndi ...

Using a data loader with react-router

I am currently working on a react app where I have implemented routes using the new data loaders from react-router-dom import { RouterProvider, createBrowserRouter, createRoutesFromElements, Route } from 'react-router-dom'; import Home fr ...

What is the reason behind allowing JavaScript to perform mathematical operations with a string type number?

let firstNum = 10; let secondNum = "10"; console.log(firstNum * secondNum); // Result: 100 console.log(secondNum * secondNum); // Result: 100 ...

What is the best way to access the EXIF data of an image (JPG, JPEG, PNG) using node.js?

In my quest to access the EXIF data of an image in order to extract GPS information such as Latitude and Longitude, I have experimented with approximately 4-5 EXIF packages available on npm/node, including exif, exif-parser, node-exif, exifr, exif-js, and ...

How can you proactively rebuild or update a particular page before the scheduled ISR time interval in Next.js?

When using NextJS in production mode with Incremental Static Regeneration, I have set an auto revalidate interval of 604800 seconds (7 days). However, there may be a need to update a specific page before that time limit has passed. Is there a way to rebui ...

Discovering hospitals in the vicinity with the help of Google Maps API and JavaScript

var MapApiApplication = { myCurrentPosition : "", mapOptions : "", marker : "", initialize : function(){ MapApiApplication.myCurrentPosition = new google.maps.LatLng(10.112293000000000000, 76.352684500000010000); M ...

Hover state remains persistent even after modal window is activated in outouchend

One of the buttons on my website has a hover effect that changes its opacity. This button is used to share information on Facebook. It's a simple feature to implement. Here is the CSS code: .social_vk, .social_fb { height: 38px; obj ...

How can I turn off Angular Grid's virtualization feature, where Angular generates div elements for the grid based on height and width positions?

Currently, I am working with an Angular grid (ag-grid) that dynamically creates div elements in the DOM to display data as the user scrolls or views different sections. As part of my testing process using Selenium WebDriver, I need to retrieve this data fr ...

Advancement of a grunt chore within a digital platform

After constructing an app with grunt, I am now in the process of developing a web interface using node and angular to interact with this app. One feature I have implemented is a button that triggers a grunt task using childProcess in NodeJS: child_process ...

Capturing the process exit event in Express: A guide

process.on('exit', async () => { console.log('updating') await campaignHelper.setIsStartedAsFalse() console.log('exit') process.exit(1) }) This code snippet is designed to trigger an update in the database before t ...

Align your content perfectly on a full-screen slick slider

Attempting to center content over a full-screen slick slider from kenwheeler.github.io/slick/, I used a flexbox but the content remains at the edge of the viewport. It seems like an issue with the position tag in the slick CSS, but I can't figure out ...

Ways to center an image without relying on margin or padding to achieve alignment

Is it possible to center all tags except for the img without using margins or paddings? header { display: flex; flex-direction: column; align-items: center; } .logo { border-radius: 50%; width: 100px; height: 100px; margin: 10px 0 0 10px; ...

Sending information to other domains and managing the feedback

As a newcomer to Jquery, I am attempting to send data to a cross-domain and need to manage the response, which is a complete HTML page. Here is the code snippet I am using: $.ajax({ url: "http://www.somehost.com/abc/xyz.php", type: "post", d ...

The issue I'm facing with my webpack-build is the exclusive appearance of the "error" that

Hey everyone! I'm currently facing an issue with importing a module called _module_name_ into my React project, specifically a TypeScript project named react-app. The module was actually developed by me and it's published on npm. When trying to i ...