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

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

问题描述

有一个示例,其中加载了2张图片:

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

我需要从canvas中删除(替换)img2。 最好是什么?

解决方案

显示图像消失时。如果你想让它透明,你可以得到图像数据,并填充透明的像素:

  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是原始图像的宽度和高度。 p>

编辑—如果你只是想要另一个图像,为什么不放一个?它将覆盖画布上的任何像素。


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?

解决方案

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

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天全站免登陆