如何用javascript擦除部分图像和擦除像素的结果是transperent? [英] How to erase partially image with javascript and result of erase pixel is transperent?

查看:93
本文介绍了如何用javascript擦除部分图像和擦除像素的结果是transperent?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的要求是用户上传图片,然后用户可以删除他们不想要的图像像素,例如他们有人的形象,他们不想要人体的像素然后他们可以擦除它。我的程序是一个Web基础。我使用js画布,但我只能通过添加白色像素来擦除,无论如何我想要白色像素是transperent。我该怎么做?

My requirement is user upload image then user can erase some pixel of image that they don't want it e.g. They have image of human and they don't want pixel of human body then they can erase its. My program is a web base. I use js canvas but I can only erase by adding white pixel to image anyway I want white pixel is transperent. How I suppose to do?

推荐答案

你可以使用合成来擦除以前绘制的图像。

Context.globalCompositeOperation =destination-out的行为如下:

Context.globalCompositeOperation="destination-out" behaves like this:

任何与上一张图重叠的后续图形将导致上一张图是已删除。

Any subsequent drawing that overlaps the previous drawing will cause the previous drawing to be "erased".

        ctx.drawImage(img,0,0);

        ctx.globalCompositeOperation="destination-out";
        ctx.beginPath();
        ctx.moveTo(0,0);
        ctx.lineTo(300,300);
        ctx.moveTo(300,0);
        ctx.lineTo(0,300);
        ctx.lineWidth=20;
        ctx.fillStyle="blue";
        ctx.stroke();

这是代码和小提琴: http://jsfiddle.net/m1erickson/puYTy/

<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" media="all" href="css/reset.css" /> <!-- reset css -->
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>

<style>
    body{ background-color: ivory; padding:20px; }
    #canvas{border:1px solid red;}
</style>

<script>
$(function(){

    var canvas=document.getElementById("canvas");
    var ctx=canvas.getContext("2d");


    var img=new Image();
    img.onload=function(){
        start();
    }
    img.src="https://dl.dropboxusercontent.com/u/139992952/stackoverflow/house-icon.png";


    function start(){

        ctx.drawImage(img,0,0);

        ctx.globalCompositeOperation="destination-out";
        ctx.beginPath();
        ctx.moveTo(0,0);
        ctx.lineTo(300,300);
        ctx.moveTo(300,0);
        ctx.lineTo(0,300);
        ctx.lineWidth=20;
        ctx.fillStyle="blue";
        ctx.stroke();
    }



}); // end $(function(){});
</script>

</head>

<body>
    <p>Composite: destination-out</p>
    <p>The lines will "erase" the existing image</p>
    <canvas id="canvas" width=300 height=300></canvas>
</body>
</html>

这篇关于如何用javascript擦除部分图像和擦除像素的结果是transperent?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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