用代码实现基于canvas在医学图像上画线,如果线画在了灰色区域上,线自动吸附到附近的白色区域周围,如果线画在了白色区域上,线自动吸附到附近的灰色区域周围
时间: 2023-05-28 15:05:14 浏览: 104
canvas画线
以下是一个简单的实现:
```html
<canvas id="canvas" width="500" height="500"></canvas>
```
```javascript
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
// 加载医学图像
const img = new Image();
img.src = 'medical_image.jpg';
img.onload = () => {
// 绘制医学图像
ctx.drawImage(img, 0, 0);
// 监听鼠标事件,画线
let isDrawing = false;
let lastX = 0;
let lastY = 0;
canvas.addEventListener('mousedown', (e) => {
isDrawing = true;
lastX = e.offsetX;
lastY = e.offsetY;
});
canvas.addEventListener('mousemove', (e) => {
if (isDrawing) {
const currentX = e.offsetX;
const currentY = e.offsetY;
// 绘制当前线段
ctx.beginPath();
ctx.moveTo(lastX, lastY);
ctx.lineTo(currentX, currentY);
ctx.stroke();
// 判断线段是否在灰色或白色区域上
const imageData = ctx.getImageData(currentX, currentY, 1, 1);
const pixel = imageData.data;
if (pixel[0] === 128 && pixel[1] === 128 && pixel[2] === 128) {
// 线段在灰色区域上,吸附到附近的白色区域周围
const whitePixels = findNearestPixels(currentX, currentY, 255);
if (whitePixels.length > 0) {
const { x, y } = whitePixels[Math.floor(Math.random() * whitePixels.length)];
ctx.lineTo(x, y);
ctx.stroke();
}
} else if (pixel[0] === 255 && pixel[1] === 255 && pixel[2] === 255) {
// 线段在白色区域上,吸附到附近的灰色区域周围
const grayPixels = findNearestPixels(currentX, currentY, 128);
if (grayPixels.length > 0) {
const { x, y } = grayPixels[Math.floor(Math.random() * grayPixels.length)];
ctx.lineTo(x, y);
ctx.stroke();
}
}
// 更新上一点
lastX = currentX;
lastY = currentY;
}
});
canvas.addEventListener('mouseup', () => {
isDrawing = false;
});
canvas.addEventListener('mouseout', () => {
isDrawing = false;
});
};
// 找到离指定点最近的指定颜色像素
function findNearestPixels(x, y, color) {
const pixels = [];
const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
const data = imageData.data;
const offset = (y * imageData.width + x) * 4;
for (let i = -1; i <= 1; i++) {
for (let j = -1; j <= 1; j++) {
const x2 = x + j;
const y2 = y + i;
const offset2 = (y2 * imageData.width + x2) * 4;
if (x2 >= 0 && x2 < imageData.width && y2 >= 0 && y2 < imageData.height &&
data[offset2] === color && data[offset2 + 1] === color && data[offset2 + 2] === color) {
pixels.push({ x: x2, y: y2 });
}
}
}
return pixels;
}
```
这段代码使用canvas绘制医学图像,并监听鼠标事件,实现了画线功能。当画线时,会检测当前线段所在像素的颜色,判断是否在灰色或白色区域上,并调用`findNearestPixels`函数找到离当前点最近的指定颜色像素,随机选择一个像素作为吸附点,并将线段的终点移动到吸附点,实现了线自动吸附的效果。
阅读全文