What are the steps to utilizing clearRect with images?

This project involves creating an analog clock for a school assignment using canvas. While I have managed to get the clock working, I am facing an issue with the clock hands leaving marks after each movement. Using the clearRect method seems to solve this problem but it also removes part of the background image (png). Is there a way to keep the image constant and only use clearRect to delete the hands?

window.onload = draw;

let myCanvas = document.getElementById("my-canvas");
var myCtx = myCanvas.getContext('2d');

var canvas = document.createElement("canvas");
var ctx = canvas.getContext("2d");

var canvas2 = document.createElement("canvas");
var ctx2 = canvas2.getContext("2d");

var radius = myCanvas.height / 2;
myCtx.translate(radius, radius);
radius = radius * 0.90

imageBack(myCtx);
setInterval(draw, 1000);

function imageBack(ctx2) {
    var img = new Image();
    img.addEventListener(
        `load`,
        function () {
            ctx2.drawImage(img, -100, -100, 200, 200);
        },
        false
    );
    img.src = "watch1.png";
}

function draw() {
    // set Time
    setTime(myCtx, radius);

    // myCtx.clearRect(-50, -50, 100, 100);
}


// set Time
function setTime(ctx, radius) {
    // ctx.clearRect(-50,-50, 100,100);

    var now = new Date();
    var hour = now.getHours();
    var minute = now.getMinutes();
    var second = now.getSeconds();

    hour = hour % 12;
    hour = (hour * Math.PI) / 6 + (minute * Math.PI) / (6 * 60) + (second * Math.PI) / (360 * 60);
    minute = (minute * Math.PI) / 30 + (second * Math.PI) / (30 * 60);
    second = (second * Math.PI) / 30;

//set hours hand
    drawHourHand(ctx, hour);
// set minutes hand
    drawMinuteHand(ctx, minute);
// set seconds hand
    drawSecondHand(ctx, second);

}

function drawHourHand(ctx, h) {
    ctx.beginPath();
    ctx.moveTo(0, 0);
    ctx.rotate(h);
    ctx.lineTo(0, -radius * 0.3);
    ctx.strokeStyle = "black";
    ctx.closePath();
    ctx.stroke();
    ctx.rotate(-h);
}

// functions drawMinuteHand and drawSecondHand are almost identical to drawHourHand 

https://i.sstatic.net/s6u9D.png

Answer №1

Display the image and initiate a timer upon loading

const bgImg = new Image();
bgImg.src = "watch1.png";
bgImg.addEventListener("load",() => setInterval(updateTime, 1000), {once: true});

After each second, clear the canvas and redraw all elements.

// utilizing one canvas element
const canvas = document.getElementById("my-canvas");
const ctx = canvas.getContext('2d');
const PI6 = Math.PI / 6;

function updateTime() {
    ctx.setTransform(1,0,0,1,0,0); // reset transform to clear canvas
    ctx.clearRect(0,0, ctx.canvas.width, ctx.canvas.height);

    var radius = ctx.canvas.height / 2;
    ctx.translate(radius, radius);
    radius *= 0.9;

    ctx.drawImage(bgImg, -100, -100, 200, 200);

    var now = new Date();
    var hour = now.getHours();
    var minute = now.getMinutes();
    var second = now.getSeconds();

    drawHourHand(ctx, (hour % 12 + minute / 60 + second / 3600) * PI6);
    drawMinuteHand(ctx, (minute + second  / 60) * PI6 / 5);
    drawSecondHand(ctx, second * PI6 / 5);    
}

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 distortion of Blender animation becomes apparent once it is imported into three.js

I've been working on a project where I'm incorporating animations into a scene using a combination of blender and three.js. It took me several hours of trial and error to finally get the model and animation successfully imported into three.js. I ...

ES6 syntax does not allow for exporting routers

Looking to convert NodeJS modules (constant xxx = require('yyy')) into ES6 format, but encountering errors when exporting the router using the export syntax in ES6: throw new TypeError('Router.use() requires a middleware function but ...

Tips for sending multiple variables in a loop as JSON data through an AJAX request

I need assistance with the code below. I am trying to pass the value[i] into a data string in a json ajax post submit. Essentially, my goal is to gather all the checked values in a form and insert them into an existing json data string using ajax. This is ...

How to Load JavaScript Files into Joomla 2.5 default.php File

When creating a component in Joomla 2.5, I encountered an issue while trying to add some JavaScript code into the layout file tmpl/default.php . To include the JavaScript files, I used the following code: $document->addScript(JURI::base() . "components ...

Analyze the length of time and provide a percentage of similarity

Is it possible to compare two durations and calculate the percentage of similarity? Suppose I have a reference duration, as well as a second duration that needs to be compared with the first one. There is an 8% tolerance level, meaning that the second du ...

The functionality of .setErrors is not applicable to FormControls within the Angular framework

When using functions like .setError with controls, I am encountering the same error message indicating that these are not recognized as functions. Below is a snippet of my code: export class AppComponent implements OnInit { // Code goes here } Within m ...

Quiz timer using JavaScript

In my HTML and JavaScript project, I am creating a quiz game where players have 15 seconds to answer each question. To implement this timer feature, I used the following code snippet: <body onload="setTimeout(Timer,15000)"> Implemented in JavaScrip ...

Using AngularJS to implement validation on radio buttons

My application is a cross-platform app that utilizes AngularJS, Monaca, and Onsen UI. Within one of the views, there exists an array of list items where each item can be associated with a random number of radio buttons. These lists are dynamically generat ...

What is the best way to shut down a browser using C#?

After clicking the Login button, I want to automatically close the browser if the login is successful. protected void btnLogin_Click(object sender, AuthenticateEventArgs e) { if (isAuthenticated) { // close the browser } } Since I am not using AJAX, thi ...

How can I choose a mesh in three.js that is not part of the loader?

I'm facing a challenge with changing the material of a mesh using three.js's mesh loader. Although I can easily change the material within the loader, I encounter an issue where I can no longer access it from an external function. It seems to be ...

Quick method for handling arrays to generate waveforms

I'm currently working on optimizing the code for my web application. While it functions, the performance is a bit slow and I am looking to make improvements: The main concepts behind the code are: The function retrieves the current buffer and conve ...

Help needed with using Regex to restrict the number of alphabetical characters allowed

Struggling with configuring RegEx's. Seeking guidance to create a RegEx with the following criteria: Only allow numbers (0-9) Allow a period (.), negative sign (-), plus sign (+), dollar sign ($), and comma (,) Do not permit any alphabetic characte ...

What is the best way to programmatically insert a new element into the DOM after it has already been rendered in Next

In my project with Next.JS 13, I am currently exploring methods to manually inject component code into an existing element in the DOM that has already been rendered. Below is the code snippet for the component: const layouts = { forgotPassword: () => ...

Acquiring the output value from the cs function using Javascript

I've hit a roadblock in my coding journey while trying to display a message to the user indicating that their data has been saved. I have a C# function that runs an SQL procedure and returns a value. Here's the C# function: Sql p = new Sql( ...

Tips for effectively passing generics to React Hooks useReducer

I am currently working with React Hooks useReducer in conjunction with Typescript. I am trying to figure out how to pass a type to the Reducer Function using generics. interface ActionTypes { FETCH, } interface TestPayload<T> { list: T[]; } inter ...

3D spinning icosahedron adorned with circles at each corner using three.js

In my project, I am working with an interactive icosahedron mesh that undergoes rotation. As part of the animation loop, circle geometries are dynamically added, and their locations are set to each vertex of the mesh at every frame. geometry = new THREE.I ...

What could be causing the state variable to fail to update in React?

Whenever a certain condition is met, a state variable should be updated. However, whenever it enters the if statement, the index remains at 0. import React, { useState, useEffect } from 'react'; import { words } from "./words.json"; im ...

Backbone - NestedModels - Issues with nested sets not triggering 'change' event

I have incorporated the Backbone nested plugin into my project. The way I set up my binding is as follows : var view = Backbone.View.extend({ initialize: function(params) { this.model.bind('change', _.bind(this.rerender, this)); ...

What is the JavaScript method for updating an HTML5 datalist to show new options?

When populating options dynamically into an HTML5 datalist, I'm facing an issue where the browser tries to display the datalist before all the options have loaded. As a result, the list either does not show up completely or only partially shows up. Is ...

Ways to divide different paths within a React Application

In my index.js file, I currently have the following code: <Router routes={routes} /> I want to move the routes section to a separate file. Here's what I've tried so far: routes.js export default ( <div> <Route path= ...