Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing an image from a canvas in HTML5

Tags:

there's an example, which loads 2 images:

    canvas = document.getElementById("canvas");     ctx = canvas.getContext("2d");      var img1 = new Image();     img.src = "/path/to/image/img1.png";     img.onload = function() {       ctx.drawImage(img, 0, 0);     };      var img2 = new Image();     img2.src = "/path/to/image/img2.png";     img2.onload = function() {       ctx.drawImage(img2, 100, 100);     }; 

I need to remove(replace) img2 from canvas. What is the best way to do it?

like image 840
Alex Ivasyuv Avatar asked Aug 11 '10 12:08

Alex Ivasyuv


People also ask

How do I remove a picture from a canvas?

Hover over the name of the photo you wish to remove. On the far right, next to the green checkmark, click the three vertical dots that appear. Select Delete, then click OK on the pop-up to confirm that you wish to delete the image from your Canvas user (personal) files.

How do I remove objects from canvas?

To delete an Object you don't want: Tap+hold your object in the Import menu on canvas. A popup menu will appear. Tap the Delete button (the trash can).

How do I delete a layer in canvas?

In the Layers panel, click the Canvas to select it. Choose Select All. Choose Edit Clear.


1 Answers

I think maybe you misunderstand what a Canvas is.

A canvas is essentially a 2 dimensional grid of pixels along an 'X' axis and a 'Y' axis. You use the API to draw pixels onto that canvas, so when you draw an image you're basically drawing the pixels that make up that image onto your canvas. The reason there is NO method that lets you just remove an image, is because the Canvas doesn't know there's an image there in the first place, it just see pixels.

This is unlike the HTML DOM (Document Object Model) where everything is a HTML element, or an actual 'thing' you can interact with, hook-up script events to etc. this isn't the case with stuff you draw onto a Canvas. When draw a 'thing' onto a Canvas, that thing doesn't become something you can target or hook into, it's just pixels. To get a 'thing' you need to represent your 'thing' in some way such as a JavaScript object, and maintain a collection of these JS objects somewhere. This how how Canvas games work. This lack of a DOM-like structure for Canvas makes rendering very fast, but can be a pain for implementing UI elements that you can easily hook into and interact with, remove etc. For that you might want to try SVG.

To answer your question, simply paint a rectangle onto your Canvas that covers up your image by using the same X/Y coords and dimensions you used for your original image, or try Pointy's solution. 'Cover-up' is probably the wrong terminology, since you're actually replacing the pixels (there are no layers in Canvas).

like image 146
Sunday Ironfoot Avatar answered Sep 23 '22 21:09

Sunday Ironfoot