首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >使用HTML5画布进行像素操作

使用HTML5画布进行像素操作
EN

Stack Overflow用户
提问于 2018-08-02 06:01:10
回答 1查看 58关注 0票数 2

好的,我正在制作一个素描应用程序。有两个画布--一个是背景图像,另一个是用户可以在上面绘制的覆盖图。我正在尝试实现一个橡皮擦功能,它将“擦除”用户在覆盖图上绘制的任何路径。到目前为止,我的erase函数如下所示:

代码语言:javascript
复制
function eraseCanvas(bottomCtx, topCtx, x, y, strokeWidth) {
            var bottomPixels = bottomCtx.getImageData(x, y, strokeWidth, strokeWidth);
            var topPixels = topCtx.getImageData(x, y, strokeWidth, strokeWidth);

            for (var i = 0; i < topPixels.data.length; i += 4) {
                topPixels.data[i] = bottomPixels.data[i];
                topPixels.data[i + 1] = bottomPixels.data[i + 1];
                topPixels.data[i + 2] = bottomPixels.data[i + 2];
                topPixels.data[i + 3] = bottomPixels.data[i + 3];
            }
            topCtx.putImageData(topPixels, x, y);
        }

本质上,我试图做的是通过使用背景中的像素重写覆盖图上的像素来擦除它们,但这并不起作用。为什么?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-08-02 06:09:57

使用dirtyWidthdirtyHeight参数将像素块从底部上下文直接复制到顶部上下文,可以不简化您的方法吗?

代码语言:javascript
复制
function eraseCanvas(bottomCtx, topCtx, x, y, strokeWidth) {

    var bottomPixels = bottomCtx.getImageData(x, y, strokeWidth, strokeWidth);

    // Directly draw bottomPixels from bottomCtx into topCtx, at the 
    // x,y coordinates, with 0,0 offset, between dimensions of 
    // strokeWidth x strongWidth 
    topCtx.putImageData(bottomPixels, x, y, 0, 0, strokeWidth, strokeWidth);
}

MDN documentation for putImageData提供了有关我提到的dirtyWidthdirtyHeight参数的更多信息

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51642841

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档