在 HTML5 中从画布中删除图像 [英] Removing an image from a canvas in HTML5

查看:22
本文介绍了在 HTML5 中从画布中删除图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有一个例子,它加载了 2 张图片:

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);
    };

我需要从画布中删除(替换)img2.什么是最佳方法?

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

推荐答案

不清楚当图像消失时您希望画布显示什么.如果你想让它透明,你可以获取图像数据并用透明像素填充它:

It's not clear what you want the canvas to show when the image is gone. If you want it to be transparent, you could get the image data and fill it with transparent pixels:

var img = ctx.createImageData(w, h);
for (var i = img.data.length; --i >= 0; )
  img.data[i] = 0;
ctx.putImageData(img, 100, 100);

其中w"和h"是原始图像的宽度和高度.

where "w" and "h" would be the width and height of your original image.

编辑 —如果你只想在那里再放一张图片,为什么不放一张呢?它会覆盖画布上的任何像素.

edit — if you just want another image there, why not just put one there? It will overwrite whatever pixels are there on the canvas.

这篇关于在 HTML5 中从画布中删除图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆