0
我的要求是用戶上傳圖像,然後用戶可以擦除他們不想要的圖像的一些像素,例如他們有人的形象,他們不希望人體的像素,然後他們可以抹去它的。我的程序是一個網絡基礎。我使用js畫布,但我只能通過將白色像素添加到圖像來擦除,無論如何,我希望白色像素是透明的。我想怎麼做?如何用javascript擦除部分圖像並擦除像素的結果是transperent?
我的要求是用戶上傳圖像,然後用戶可以擦除他們不想要的圖像的一些像素,例如他們有人的形象,他們不希望人體的像素,然後他們可以抹去它的。我的程序是一個網絡基礎。我使用js畫布,但我只能通過將白色像素添加到圖像來擦除,無論如何,我希望白色像素是透明的。我想怎麼做?如何用javascript擦除部分圖像並擦除像素的結果是transperent?
您可以使用合成來「擦除」先前繪製的圖像。
Context.globalCompositeOperation =」目的地出」的行爲是這樣的:
在任何隨後的拉伸重疊以前的圖將導致前圖被‘擦除’。
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>
我已完成+1,因爲這應該工作,但由於帆布的一些實現無法正確渲染某些合成模式的測試是必需的。 (即使在強大的Chrome上)。 – GameAlchemist
感謝您的解答。 @markE – cavaliercyber