我在写一个Web应用程序,我需要注释图像。为此,我使用html5的画布。感谢网络,我发现许多类似的代码。但是在开发代码后我遇到了问题。擦除图像画布上的线条而不影响背景
context.clearRect(pos.x,pos.y,pos.x,pos.y);
这是我用来清除画布中的代码的代码。我期待的代码是擦除鼠标指针所在的位置。但是,即使鼠标指针在距离该线较近的地方,代码所做的也是删除该行。
编辑:我发现擦除的问题。 clearRect()的语法是
context.clearRect(x,y,width,height);
正如我给pos.x和pos.y作为宽度和高度分别是擦除的广大地区。现在我将这两个值更改为5,5,并且我可以擦除指针所在的位置。
此外,我需要保存注释完全注释后的图像。我将图像保持为画布的背景。我正在画布上画线。点击查看图片时,我只能看到线条。请检查我的代码告诉我如何执行这两个操作。这是我的代码。
<%@ taglib uri="/struts-tags" prefix="s" %>
<html>
<head>
<title>Success: Upload User Image</title>
<style>
canvas { background:url("images/<s:property value="userImageFileName"/>") ;
background-size: 100% 100%;
background-repeat: no-repeat;}
</style>
</head>
<body>
<h2>utStruts2 File Upload Example</h2>
<img id="result" src="images/<s:property value="userImageFileName"/>" width="565" height="584" class="annotatable"/>
<canvas id="myCanvas" width="565" height="584" style="border:1px solid #d3d3d3;" >
Please use a modern browser like Firefox, Chrome, Safari
</canvas>
<input type="button" value="draw" onClick="draw()">
<input type="button" value="eraser" onClick="erase()">
<canvas id="canvas2" width="565" height="584" hidden="true"></canvas>
<script>
var canvas = document.getElementById('myCanvas');
var coord = document.getElementById('coord');
var context = canvas.getContext('2d');
var canvas2 = document.getElementById('canvas2');
var cantext2 = canvas2.getContext('2d');
function draw(){
mode="draw";
operate(mode);
}
function erase(){
mode="erase";
operate(mode);
}
function operate(mode)
{
var mousedown = false;
context.strokeStyle = '#0000FF';
context.lineWidth = 5;
canvas.onmousedown = function(e) {
var pos = fixPosition(e, canvas);
mousedown = true;
context.beginPath();
context.moveTo(pos.x, pos.y);
//return false;
};
canvas.onmousemove = function(e) {
var pos = fixPosition(e, canvas);
if (mousedown) {
if(mode=="draw"){
context.lineTo(pos.x, pos.y);
context.stroke();
}
if(mode=="erase"){
context.clearRect(pos.x,pos.y,pos.x,pos.y);
context2.drawImage(canvas, 0, 0);
context.clearRect(0, 0, 565, 584);
context.drawImage("images/<s:property value="userImageFileName"/>", 0, 0);
context.drawImage(canvas2, 0, 0);
}
}
};
canvas.onmouseup = function(e) {
mousedown = false;
};
function fixPosition(e, gCanvasElement) {
var x;
var y;
x = e.pageX;
y = e.pageY;
x -= gCanvasElement.offsetLeft;
y -= gCanvasElement.offsetTop;
return {x:x, y:y};
}
}
</script>
</body>
</html>