<html>
<head> </head>
<body>
<canvas
id="canvas"
style="display:block;margin:0 auto;border:1px solid #ccc"
>您的浏览器不支持canvas</canvas
>
<canvas
id="offCanvas"
style="display:none;margin:0 auto;border:1px solid #ccc"
>您的浏览器不支持canvas</canvas
>
</body>
</html>
<script>
var canvas = document.getElementById('canvas')
var context = canvas.getContext('2d')
var offCanvas = document.getElementById('offCanvas')
var offContext = offCanvas.getContext('2d')
var scale = null
var img = new Image()
var isMouseDown = false
window.onload = function () {
canvas.width = 800
canvas.height = 800
img.src = 'xxx-lg.jpg'
img.onload = function () {
offCanvas.width = img.width
offCanvas.height = img.height
scale = offCanvas.width / canvas.width
context.drawImage(img, 0, 0, canvas.width, canvas.height)
offContext.drawImage(img, 0, 0)
}
}
canvas.onmousedown = function (e) {
e.preventDefault()
console.log(e.clientX, e.clientY)
var point = windowToCanvas(e.clientX, e.clientY)
console.log(point.x, point.y)
isMouseDown = true
drawfangdajing(true, point)
}
canvas.onmousemove = function () {
e.preventDefault()
if (isMouseDown) {
var point = windowToCanvas(e.clientX, e.clientY)
drawfangdajing(true, point)
}
}
canvas.onmouseup = function () {
e.preventDefault()
isMouseDown = false
drawfangdajing(false)
}
canvas.onmouseout = function () {
e.preventDefault()
isMouseDown = false
drawfangdajing(false)
}
function windowToCanvas(x, y) {
var bbox = canvas.getBoundingClientRect()
return { x: x - bbox.left, y: y - bbox.top }
}
function drawfangdajing(isShow, point) {
context.clearRect(0, 0, canvas.width, canvas.height)
context.drawImage(img, 0, 0, canvas.width, canvas.height)
if (isShow) {
var img_cx = point.x * scale
var img_cy = point.y * scale
var mr = 200
var sx = img_cx - mr
var sy = img_cy - mr
var dx = point.x - mr
var dy = point.y - mr
context.save()
context.lineWidth = 10
context.strokeStyle = '#069'
context.stroke()
context.beginPath()
context.arc(point.x, point.y, mr, 0, Math.PI * 2)
context.clip()
context.drawImage(
offCanvas,
sx,
sy,
2 * mr,
2 * mr,
dx,
dy,
2 * mr,
2 * mr
)
context.restore()
}
}
</script>