在HTML5画布上擦除图像的一部分? [英] Erasing Parts of an Image on HTML5 Canvas?

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

问题描述

我有一个HTML5画布.我正在使用 KineticJS(KonvaJS)画布库.在空白画布上,我如下图所示拖动图像.现在,我想创建一个圆形,可以用来擦除图像的一部分.图像中的红色圆圈是橡皮擦.

I have an HTML5 Canvas. I am using the KineticJS(KonvaJS) canvas library. On a blank canvas I dram an image as shown in the figure below. Now I want to create a circle Shape which can be used to erase parts of the image. The red circle in the image is the eraser.

如何在HTML5画布上擦除图像的一部分?

推荐答案

您可以使用合成"来擦除"像素.

You can use Compositing to "erase" pixels.

特别是您使用destination-out合成.

KineticJS不支持合成,但是您仍然有两个选择:

KineticJS does not support compositing, but you still have a couple of options:

(注意:KineticJS已经成为KonvaJS,我还没有检查KonvaJs是否支持合成.如果现在支持,只需在KonvaJS内使用destination-out合成)

选项1:使用原生画布元素作为Kinetic.Image源

  • 使用var c=document.createElement

将画布调整为图像大小,

Resize the canvas to image size,

drawImage将您的图像粘贴到画布上

drawImage your image onto the canvas,

创建一个Kinetic.Image并将其image属性设置为对本机画布的引用. Kinetic.Image将显示绘制到本机画布上的任何内容.

Create a Kinetic.Image and set its image property to a reference to the native canvas. The Kinetic.Image will display whatever is drawn onto the native canvas.

var kImage=new Kinetic.Image({
...
image:c,
...

  • 设置画布合成以使新图形擦除"现有像素:

  • Set the canvas Compositing to cause new drawings to "erase" existing pixels:

    c.globalCompositeOperation='destination-out';
    

  • 收听您的圆形橡皮擦上的拖动事件.使用这些事件在画布上绘制一个与Kinetic圆形橡皮擦移动一样移动的圆圈.由于画布的合成设置为擦除",因此画布上的新圆圈绘制将擦除画布上的图像.

  • Listen for drag events on your circle-eraser. Use those events to draw a circle on the canvas that move just like the Kinetic circle-eraser moves. Since the canvas's compositing is set to "erase", new drawings of the circle on the canvas will erase the image on the canvas.

    您的Kinetic.Image恰好反映了其画布源(变量c),因此您的Kinetic.Image还将显示响应Kinetic圆橡皮擦运动而被擦除的图像.

    Your Kinetic.Image exactly reflects its canvas source (var c), so your Kinetic.Image will also display the image being erased in response to the Kinetic circle-eraser movements.

    选项2:使用Kinetic.Shape

    您可以通过在单独的图层上创建Kinetic.Shape并使用以下方法获取对本机画布上下文的引用,来执行与Option#1相同的操作:

    You can do the same operation as Option#1 by creating a Kinetic.Shape on a separate layer and getting a reference to the native canvas context using:

    var ctx = myShapeLayer.getContext()._context;
    

    这是一个较弱的选择,因为KineticJS将重绘形状-导致删除操作被撤消.因此,您必须执行额外的步骤,保存所有圈子擦除器的移动并重播这些移动(在drawFunc中)以重做擦除.

    This is a weaker option because KineticJS will redraw the shape--causing your erasing to be undone. Therefore you must do the additional step of saving all your circle-eraser's movements and replaying those movements (in drawFunc) to redo your erasing.

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

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