<!DOCTYPE html
>
<html lang
="en">
<head
>
<meta charset
="UTF-8">
<meta name
="viewport" content
="width=device-width, initial-scale=1.0">
<title
>Document
</title
>
<style
>
canvas
{
border
: 1px solid red
;
}
</style
>
</head
>
<body
>
<canvas width
="300" height
="300" id
="canvas1"></canvas
>
</body
>
</html
>
<script
>
window
.onload = function () {
var mycanvas
= document
.getElementById('canvas1');
var ctx
= mycanvas
.getContext('2d');
dw();
function dw() {
mycanvas
.onmousedown = function () {
let y1
= event
.offsetY
;
let x1
= event
.offsetX
;
mycanvas
.onmousemove = function () {
let y
= event
.offsetY
;
let x
= event
.offsetX
;
ctx
.beginPath();
ctx
.lineCap
= 'round';
ctx
.lineJoin
= 'round'
ctx
.lineWidth
= 10;
ctx
.lineTo(x1
, y1
);
ctx
.lineTo(x
, y
);
ctx
.lineWidth
= 10;
ctx
.stroke();
x1
= x
;
y1
= y
}
}
}
mycanvas
.onmouseup = function () {
mycanvas
.onmousedown
= null;
mycanvas
.onmousemove
= null;
dw();
}
mycanvas
.onmouseleave = function () {
mycanvas
.onmousedown
= null;
mycanvas
.onmousemove
= null;
dw();
}
}
</script
>
如果你的画板有断点问题,那么你的点设置的一定有问题,你要在鼠标按下的时候获取此时的点,鼠标移动的时候也要获取当前的点,最后绘制的时候从鼠标按下的点开始到移动的点,这样才会形成一条完整的线段。
转载请注明原文地址:https://ipadbbs.8miu.com/read-24895.html