У меня небольшой html5-проект, в котором нужно нарисовать линию на изображении с помощью canvas.Ниже приведен пример кода, который я нашел на форуме.
<!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; }
#canvas{
border:1px solid red;
}
</style>
<script>
$(function(){
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var imageOpacity=1;
var canvasPos = canvas.getBoundingClientRect();
var dragging = false;
var img=new Image();
img.onload=start;
img.src="http://res.publicdomainfiles.com/pdf_view/84/13939501819528.png";
function start(){
canvas.width=canvas.width=img.width;
canvas.height=img.height;
ctx.strokeStyle="green";
ctx.lineWidth=3;
$("#canvas").mousedown(function(e){handleMouseDown(e);});
$("#canvas").mousemove(function(e){handleMouseMove(e);});
$("#canvas").mouseup(function(e){handleMouseUp(e);});
$("#canvas").mouseout(function(e){handleMouseUp(e);});
// redraw the image
drawTheImage(img,imageOpacity);
}
function drawTheImage(img,opacity){
ctx.globalAlpha=opacity;
ctx.drawImage(img,0,0);
ctx.globalAlpha=1.00;
}
function handleMouseDown(e){
var pos = getCursorPosition(e);
dragging = true;
ctx.strokeStyle = 'green';
ctx.lineCap = 'round';
ctx.lineJoin = 'round';
ctx.lineWidth = 3;
ctx.beginPath();
ctx.moveTo(pos.x, pos.y);
}
function handleMouseUp(e){
dragging = false;
}
function handleMouseMove(e){
var pos, i;
if (!dragging) {
return;
}
pos = getCursorPosition(e);
ctx.lineTo(pos.x, pos.y);
ctx.stroke();
}
function getCursorPosition(e) {
return {
x: e.clientX - canvasPos.left,
y: e.clientY - canvasPos.top
};
}
});
</script>
</head>
<body>
<canvas id="canvas"></canvas>
</body>
</html>
У меня возникла проблема, когда я нарисовал линию в нижней части изображения.Линия не рисуется для большого изображения, скрипт работает нормально только для маленького изображения (например, большое изображение в приведенном выше коде). Любые советы или рекомендации будут с благодарностью, спасибо.