基于canvas在浏览器图片上画线 在白色区域周围画线,线自动吸附到白色区域边界,在灰色区域周围画线 线自动吸附到灰色区域附近
时间: 2023-05-28 12:05:00 浏览: 48
实现思路:
1. 获取图片元素和canvas元素
2. 在canvas上绘制图片
3. 绘制白色和灰色区域的路径
4. 绑定鼠标移动事件,在鼠标移动时根据鼠标位置绘制线条,并进行吸附处理
5. 完成绘制
代码实现:
```html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Canvas绘制图片</title>
<style type="text/css">
canvas{
border:1px solid #ccc;
}
</style>
</head>
<body>
<img id="img" src="image.jpg" style="display:none;">
<canvas id="canvas"></canvas>
<script type="text/javascript">
var img = document.getElementById('img');
var canvas = document.getElementById('canvas');
canvas.width = img.offsetWidth;
canvas.height = img.offsetHeight;
var ctx = canvas.getContext('2d');
ctx.drawImage(img, 0, 0, img.offsetWidth, img.offsetHeight);
ctx.strokeStyle = '#000';
// 绘制白色区域
ctx.beginPath();
ctx.moveTo(50, 50);
ctx.lineTo(150, 50);
ctx.lineTo(150, 150);
ctx.lineTo(50, 150);
ctx.closePath();
ctx.fillStyle = '#fff';
ctx.fill();
// 绘制灰色区域
ctx.beginPath();
ctx.moveTo(250, 50);
ctx.lineTo(350, 50);
ctx.lineTo(350, 150);
ctx.lineTo(250, 150);
ctx.closePath();
ctx.fillStyle = '#ccc';
ctx.fill();
canvas.addEventListener('mousemove', function(e){
var x = e.offsetX;
var y = e.offsetY;
if(x > 50 && x < 150 && y > 50 && y < 150){
// 在白色区域内,吸附到边缘
if(x < 100){
x = 50;
}else{
x = 150;
}
if(y < 100){
y = 50;
}else{
y = 150;
}
}else if(x > 250 && x < 350 && y > 50 && y < 150){
// 在灰色区域内,吸附到附近
if(x < 300){
x = x - 50;
}else{
x = x + 50;
}
if(y < 100){
y = y - 50;
}else{
y = y + 50;
}
}
drawLine(x, y);
});
function drawLine(x, y){
ctx.beginPath();
ctx.moveTo(x, y);
ctx.lineTo(x+10, y+10);
ctx.stroke();
}
</script>
</body>
</html>
```