我在寫一個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>