Enhance the appearance of the canvas

A dilemma I currently face involves creating a basic canvas and incorporating an <input type="color">. My goal is to change the color of a specific shape when the color value is changed. Take a look at my code below:

var colorRect = '#000';

var ball = document.getElementById("canvas");
var ctx = ball.getContext("2d");
var ctx1 = ball.getContext("2d");
ctx1.fillStyle = colorRect;
ctx1.fillRect(0,0,200,200);
ctx1.save();

//Left eye
ctx.fillStyle = '#fff';
ctx.fillRect(50,80,10,10);

//Right eye
ctx.fillStyle = '#fff';
ctx.fillRect(150,80,10,10);

//Nose
ctx.fillStyle = '#fff';
ctx.fillRect(100,110,10,20);

//Mouth

ctx.fillStyle = 'red';
ctx.fillRect(60,150,100,10);

$('#favcolor').on('change',function(){
  colorRect = $(this).val();
  ctx1.fillStyle = $(this).val();
  ctx1.fillRect(0,0,200,200);
});

To see it in action, visit this link: http://jsbin.com/inewum/1. The issue I'm facing is that the updated style seems to override everything, causing the eyes and mouth to disappear. I simply want to update the style without losing those elements.

Answer №1

If you want to make changes, you must redraw the illustration. Develop a drawing routine and variables for color states. Whenever you modify something, simply redraw it with the updated colors.

Your task involves adjusting the context fill style and drawing a rectangle on it. This is why the eyes and mouth vanish from view.

Try implementing these modifications and check out the DEMO:

$(function () {

    draw();
    $('#favcolor').on('change', function () {
        colorRect = $(this).val();
        draw();
    });

});

var colorRect = '#000';

function draw() {

    var canvas = document.getElementById("canvas");
    var context = canvas.getContext("2d");
    var context1 = canvas.getContext("2d");
    context1.fillStyle = colorRect;
    context1.fillRect(0, 0, 200, 200);
    context1.save();

    //Left eye
    context.fillStyle = '#fff';
    context.fillRect(50, 80, 10, 10);

    //Right eye
    context.fillStyle = '#fff';
    context.fillRect(150, 80, 10, 10);

    //Nose
    context.fillStyle = '#fff';
    context.fillRect(100, 110, 10, 20);

    //Mouth
    context.fillStyle = 'red';
    context.fillRect(60, 150, 100, 10);
}

Answer №2

In HTML5 canvas, the shapes like rectangles, circles, and lines are considered non-substantive objects, unlike JavaScript DOM objects. This means you cannot directly manipulate them individually; instead, you must redraw the entire canvas to make changes to specific elements.

Answer №3

If you're looking for a different approach, SVG might be the solution for you. SVG elements can be manipulated just like regular HTML elements.

Check out this example using SVG: http://jsbin.com/inewum/15/edit

You can simplify the script to:

$('#favcolor').on('change',function(){
    $('.face').css({
      'fill': $(this).val()
    });
});

Instead of using canvas, consider using this SVG code:

<svg height=200 width=200 viewBox='0 0 200 200'>
   <rect width=200 height=200 class="face" />
   <!-- left eye -->
   <rect x=50 y=80 width=10 height=10 fill="white"/>
   <!-- right eye -->
   <rect x=150 y=80 width=10 height=10 fill="white"/>
   <!-- nose -->
   <rect x=100 y=110 width=10 height=20 fill="white"/>
   <!-- mouth -->
   <rect x=60 y=150 width=100 height=10 fill="red"/>
</svg>

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

When a child is added to a parent in Angular UI Tree, it automatically appears in all parent nodes as well

I've been experimenting with the drag and drop feature of Angular UI Tree, and I've encountered a puzzling issue. The JSON data is fetched from my services. Upon receiving it in my controller, I need to format it correctly by adding an empty arra ...

There appears to be an issue with the functionality of the Bootstrap toggle tab

Currently, I am facing a toggle issue and having trouble pinpointing the root cause as there are no errors appearing in the console. The problem involves two tabs that can be toggled between - "pay" and "method". Initially, the default tab displayed is "pa ...

Menu selection popper JavaScript

Struggling to create a dropdown menu and encountering this error: "Uncaught Error: Bootstrap dropdown require Popper.js (https://popper.js.org) at bootstrap.min.js:6 at bootstrap.min.js:6 at bootstrap.min.js:6" Explored various solutions in f ...

Showcasing the information stored within my li element, I am able to access and view the data through my console

I want to showcase the data in the browser Upon hitting the api call, I retrieve the data in my console. The challenge lies in displaying the data within my li tag. Below are snippets of my relevant code and the entire code can be found in the gist links p ...

Is the ID selector the quickest method in jQuery and CSS?

Which is the optimal choice in jQuery/javascript for speed? $('#myID .myClass') or $('.myClass') What is the preferred option to utilize in CSS? #myID .myClass{} or .myClass{} In hindsight, I realize my explanation was insuffici ...

The rotation of the camera in three.js around the Y Axis appears to be improper

Our project involves developing a VR/Stereoscopic web application using three.js to showcase the camera's viewing angle. For instance, we have set up a "room" scenario with the camera positioned in the center. The camera's rotation is linked to ...

Download a file on button click using JavaScript with data extracted from the DOM

I am looking to create a download feature where a user can click a button on the webpage, triggering a JavaScript method to capture the contents of a DOM element and prompt the user for a download. After successfully capturing the DOM element in a JavaScr ...

Utilizing a combination of HTML, AJAX, and PHP, transfer an HTML input array via AJAX to a PHP webpage

Despite trying numerous similar solutions, none of them have proven effective for my issue. Within a form, users can input an unspecified amount of select options that can be added as needed using AJAX. My goal is to post this array to a PHP page via AJAX ...

Trouble persisting values with Heroku due to variable issues

Here is a concise example: let value = null; const getValues = () => { fetch('/third-party-api') .then(res => res.json()) .then(data => { value = data; }) } getValues(); app.get("/values", async (req, res) ...

Angular directive becomes disabled when transferred between different DOM elements

In my app, I utilize a modal service that handles the opening and closing of modals. The modal retrieves its content from a specific div with an ID located within a hidden container element. This process typically functions correctly. The issue I am encou ...

struggling to preserve form data using PHP and MySQL

I am facing an issue with a page that needs to display a form with checkboxes, save the results in the database, and then load the page with the checkboxes checked based on the stored data. Although I realize that my solution of floating "checked" is not ...

What are the different ways to format a .SQL file in real-time when it is located on an internal website?

In order to upload files to my local server for future reference and training purposes, I am looking for a way to easily format SQL and C# code. I believe there must be a JavaScript library available that can meet these specific needs. My ideal solution ...

How does the Paginate Pipe effectively retrieve the array length in an Angular 2 application?

I find myself in an interesting situation where I have a piece of code that is functioning within my Angular 2 application - it's generating the correct value, but the method behind its success is unclear to me. Specifically, I am using ng2-paginatio ...

The updated version 2.1.4 has rendered the Jquery code incompatible, which was previously functioning perfectly on version 1.11.0

After updating from Jquery 1.11.0 to version 2.1.4, I am experiencing issues with this code $('input:checkbox').on('click', function () { $(this).closest('tr').find('input:checkbox').removeAttr('checked&ap ...

Is it possible to create HTML content directly from a pre-rendered canvas element or input component like a textbox?

As I delve into learning JavaScript and HTML5, a couple of questions have sparked my curiosity: 1) Can we create HTML from a Canvas element(s)? For instance, imagine having a Canvas shape, and upon clicking a button, it generates the HTML5 code that displ ...

Create a horizontal scrolling div with a fixed position

Even though this topic has been discussed numerous times, I have not found any solutions that work for me. My webpage has a sidebar on the left with position:fixed in CSS, and I want it to scroll horizontally along with the rest of the content. For the he ...

Including a Pinterest image hover widget following the completion of an Ajax load

I have implemented the Pinterest image hover widget on my website to allow users to easily pin images to their Pinterest accounts. You can find the widget here. (Make sure to click the image hover radio button under button type to see the one I am using.) ...

Troubleshooting: jQuery AJAX Post - Issue with Greater than conditional not functioning as expected

Having an issue with a conditional in my code. Everything is functioning properly except for this specific line. <if condition="$show['member']"> <script type="text/javascript" > $(function() { $("#submitbutton$post[postid]").click(f ...

Using Selenium and Java, one can extract the "Effective Date" text from the text node within the th node

Can someone help me with extracting the text Effective Date from the image provided below? What would be the correct way to create an xpath for this? Below is the snapshot of the HTML: https://i.sstatic.net/LFBDG.png ...

Exploring the creation of CSS animations using box-shadow effects

Looking to create a CSS animation where part of a line (200px) changes color like a gradient. Any ideas on how to achieve this effect? Below is the current code being used: * { margin: 0; padding: 0 20px; } h1 { text-align: center; } ...