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.