I pressed the button but the globalCompositeOperation isn't working as expected. How can I make it function correctly to achieve the desired output like the second canvas?

<!DOCTYPE html>
<html>
<head>
  <title>Canvas Compositing Tutorial</title>
</head>
<body>

  <canvas id="myCanvas" width="200" height="200" style="border: 1px solid"></canvas> <br>

  <button onclick="performComposite()">Perform Composite</button> <br>

  <p>Expected Result : </p>
  
  <canvas id="myResultCanvas" width="200" height="200" style="border: 1px solid"></canvas>

  <script type="text/javascript">

    // First Canvas

    let myCanvas = document.getElementById('myCanvas');
    let ctx = myCanvas.getContext('2d');
    ctx.fillStyle = "red";
    ctx.fillRect(10, 10, 100, 100);

    function performComposite() {
      ctx.globalCompositeOperation = "source-atop";
    };

    ctx.fillStyle = "blue";
    ctx.arc(110, 110, 80, 0 * Math.PI, 2 * Math.PI);
    ctx.fill();

    // Second Canvas

    let myResultCanvas = document.getElementById('myResultCanvas');
    let resultCtx = myResultCanvas.getContext('2d');
    resultCtx.fillStyle = "red";
    resultCtx.fillRect(10, 10, 100, 100);

    resultCtx.globalCompositeOperation = "source-atop";

    resultCtx.fillStyle = "blue";
    resultCtx.arc(110, 110, 80, 0 * Math.PI, 2 * Math.PI);
    resultCtx.fill();

  </script>
  <br/>
</body>
</html>

After clicking the button, the globalCompositeOperation is not working...how can i do that for the expected answer?
The expected answer is in the second canvas or second image...
Why is it not working...?

Answer №1

Referencing a paragraph from the Compositing and clipping tutorial on developer.mozilla.org:

When setting globalCompositeOperation = type, you are defining the compositing operation to be used when drawing new shapes. The type parameter is a string representing one of the twelve available compositing operations.

The important takeaway here is: '...when drawing new shapes...'

In other words, altering the composite operation for your canvas at the end of the drawing process does not impact shapes drawn earlier.

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 reason behind the browser crashing when a scrollbar pseudo-class is dynamically added to an iframe?

1. Insert a new iframe into your HTML: <iframe id="iframe-box" onload=onloadcss(this) src="..." style="width: 100%; border: medium none; "></iframe> 2. Incorporate the following JavaScript code into your HTML file ...

JavaScript promises do not guarantee the execution of the loop

There was a block of Javascript code that I needed to modify. Initially, the code looked like this: if(!this.top3){ const promises = this.images.map((el, index) => { return this.getData(el.title, index); }); return Promise.all(promise ...

JQuery button.click() handler executes without a user click

Currently, I am in the process of tidying up the code for my auction game. However, I have encountered an issue where my function is triggered immediately after endAuction() is called rather than waiting for the button click event. Unfortunately, I am no ...

Activate Button upon Textbox/Combobox/RadDatePicker Modification through JavaScript

On my ASP.NET form, I have various input elements including textboxes, dropdowns, date pickers, and update buttons. My goal is to enable the update button whenever a user makes a change in any of these fields. To achieve this, I applied a specific CSS cla ...

React - verifying properties

Here's a question that I've been pondering. In many situations, we find ourselves needing to check if props are undefined. But what about nested props? For example, let's say we have: this.props.data.income.data1.value.chartData and we wa ...

"Transferring a variable from the parent Layout component to its children components in Next

I am trying to figure out how to effectively pass the variable 'country' from the Layout component to its children without using state management. Basically, I want to drill it down. import { useState, useEffect } from 'react' import La ...

Having difficulty sending emails with attachments using AngularJS

While using Angular, I encountered an issue when sending an email with an attachment. The response I received contained the data code of the file instead of its actual format. See example: https://i.stack.imgur.com/vk7X8.png I am unsure what is causing t ...

Retrieve data from a JSON array using either JavaScript or PHP

Check out my code snippet: const newData = [{"new_id":"1","new_no":"1","total":"N.A"},{"new_id":"2","new_no":"3","total":"4"},{"new_id":"2","new_no":"4","total":"5"}]; Now, I need to extract specific details from this JSON data based on the 'new_no& ...

Tips for utilizing Variant on an overridden component using as props in ChakraUI

I created a custom Component that can be re-rendered as another component using the BoxProps: export function Label ({ children, ...boxProps }: BoxProps) { return ( <Box {...boxProps}> {children} </Box> ); } It functio ...

What is the best way to generate an array from JSON data while ensuring that the values are not duplicated?

Upon receiving a JSON response from an API, the structure appears as follows: { "status": "success", "response": [ { "id": 1, "name": "SEA BUSES", "image": null }, { "id": 2, ...

Handling error reporting using JSON in jQuery AJAX post success

UPDATE: I have resolved the PHP errors mentioned in previous Answers, however, the issue still persists. I am attempting to implement an error message display in case of a failed POST request and a success message for successfully completed requests. Curr ...

Creating a wrapper component to enhance an existing component in Vue - A step-by-step guide

Currently, I am utilizing quasar in one of my projects. The dialog component I am using is becoming redundant in multiple instances, so I am planning to create a dialog wrapper component named my-dialog. my-dialog.vue <template> <q-dialog v-bin ...

Executing multiple Ajax requests on CodeIgniter 3 from two separate pages

I am facing a critical need for a code review and unfortunately, I am unsure of where else to seek assistance besides here. Let me outline my current task: I am working on a user profile page that is designed to showcase users' comments. Users have t ...

My goal is to design a dynamic textbox for a website that allows users to customize the text in any format they desire

I want to create a versatile textbox on my website that allows users to change the text format as they desire. Unfortunately, I am facing some issues with implementing this feature. Here is the code I have developed so far. <body> <h1>< ...

Exploring the capabilities of arrays within Ajax

Below is the original code I wrote in JavaScript: var wt_val = []; for (i = 0; i<human_wt.length; i++){ var mult; mult = data_list[basket_list[button_port_name][i]].map(x => x*(wt[i]/100)); wt_val.push(mult); ...

Utilizing Javascript / jQuery to eliminate specific CSS styles

I am facing an issue with the CSS code for a table positioned at the bottom of the screen. The current code includes a filter specifically for IE 8, but I need to make it compatible with IE 10 as well by removing the filter and adding a background color. ...

Using Local Storage to store arrays in JavaScript/jQuery

Currently, I am implementing a set of multiple buttons each containing data-id and data-name Below is my concept along with some sample code for reference: $(".clickCompare").click(function ({ var id = $(this).attr('data-id'); var ...

Is there a way to restrict my input to only 10 numbers without allowing any characters?

Is there a way to restrict the phone number input to only allow 10 numbers and exclude any other characters? Currently, setting the maxLength attribute limits the characters to 10 but allows additional characters as well. If I change the type attribute to ...

Refreshing a Thymeleaf table dynamically without having to reload the entire page

I am currently using the Thymeleaf attribute to render data, but I am now looking to add a "Search" button without reloading the page. Within the attribute departments, I am rendering a List<Department> from the database. While I understand how to a ...

Is there a way to identify and count duplicate data-items within an array, and then showcase this information using a react view?

If we have an array like this: [{id: 1, name: "chocolate bar"}, {id:2, name: "Gummy worms"}, {id:3, name:"chocolate bar"}] Is there a way to show on the dom that we have "2 chocolate bars and 1 Gummy Worms"? ...