擦除在图像画布HTML5上绘制的颜色线

时间:2015-09-29 11:07:20

标签: javascript css html5 canvas

我有一个带图像的画布,上面我画了一个红色的矩形。现在我要在用户的触摸事件上清除那个红色矩形,我的问题是它也清除了图像。它没有显示图像。

使用代码:

<!DOCTYPE html>
<html>
<body>

<p>Image to use:</p>
<img id="scream" width="220" height="277" src="img_the_scream.jpg" alt="The Scream">

<p>Canvas:</p>
<canvas id="myCanvas" width="240" height="297" style="border:1px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.
</canvas>

<script>
window.onload = function() {
    var c = document.getElementById("myCanvas");
    var ctx = c.getContext("2d");
    var img = document.getElementById("scream");
    ctx.drawImage(img, 10, 10);
     ctx.fillStyle = "red";
    ctx.fillRect(0, 0, 300, 150);
     ctx.clearRect(20, 20, 100, 50);
}
</script>

</body>
</html>

我的结果是: enter image description here

我的期望:enter image description here

另外,我已经检查了这个Fiddle,现在如何再次填充该删除区域的颜色。

2 个答案:

答案 0 :(得分:0)

基本上你需要创建一个rect而不是fillRect,一旦你创建了rect然后绘制了你的图像,你提供的图像将用于填写你画的矩形

jsFiddle:https://jsfiddle.net/CanvasCode/308tv9dL/3/

的javascript

render = function () {
    var c = document.getElementById("myCanvas");
    var ctx = c.getContext("2d");
    var img = document.getElementById("scream");

    ctx.rect(25, 25, 150, 150);
    ctx.clip();

    ctx.drawImage(img, 0, 0, 300, 200);
}

render();

答案 1 :(得分:0)

window.onload = function() {
  var c = document.getElementById("myCanvas");
    var ctx = c.getContext("2d");
    var img = document.getElementById("scream");
    ctx.drawImage(img, 10, 10);
  var cOver = document.getElementById("myCanvasOver");
    var overtx = cOver .getContext("2d");
     overtx .fillStyle = "red";
    overtx.fillRect(0, 0, 300, 150);
    overtx.clearRect(20, 20, 100, 50);
}
<p>Image to use:</p>
<img id="scream" src="http://www.w3schools.com/html/img_the_scream.jpg" alt="The Scream" width="220" height="277">

<p>Canvas:</p>
<div style='position:relative;height:300px;width:250px;'>
<canvas id="myCanvas" width="250" height="300"
style="border:1px solid #d3d3d3;"></canvas>
<canvas id="myCanvasOver" width="250" height="300"
style="position:absolute;top:0;right:0;">
</canvas>
</div>