我想使用鼠标在 HTML 画布上绘图(例如,绘制签名、绘制名称……)
我将如何实施呢?
原文由 MartinJoo 发布,翻译遵循 CC BY-SA 4.0 许可协议
我想使用鼠标在 HTML 画布上绘图(例如,绘制签名、绘制名称……)
我将如何实施呢?
原文由 MartinJoo 发布,翻译遵循 CC BY-SA 4.0 许可协议
我认为,这里的其他例子太复杂了。这个更简单,只有 JS …
// create canvas element and append it to document body
var canvas = document.createElement('canvas');
document.body.appendChild(canvas);
// some hotfixes... ( ≖_≖)
document.body.style.margin = 0;
canvas.style.position = 'fixed';
// get canvas 2D context and set him correct size
var ctx = canvas.getContext('2d');
resize();
// last known position
var pos = { x: 0, y: 0 };
window.addEventListener('resize', resize);
document.addEventListener('mousemove', draw);
document.addEventListener('mousedown', setPosition);
document.addEventListener('mouseenter', setPosition);
// new position from mouse event
function setPosition(e) {
pos.x = e.clientX;
pos.y = e.clientY;
}
// resize canvas
function resize() {
ctx.canvas.width = window.innerWidth;
ctx.canvas.height = window.innerHeight;
}
function draw(e) {
// mouse left button must be pressed
if (e.buttons !== 1) return;
ctx.beginPath(); // begin
ctx.lineWidth = 5;
ctx.lineCap = 'round';
ctx.strokeStyle = '#c0392b';
ctx.moveTo(pos.x, pos.y); // from
setPosition(e);
ctx.lineTo(pos.x, pos.y); // to
ctx.stroke(); // draw it!
}
原文由 Matěj Pokorný 发布,翻译遵循 CC BY-SA 3.0 许可协议
2 回答1.4k 阅读✓ 已解决
2 回答829 阅读✓ 已解决
4 回答1.6k 阅读
1 回答1.1k 阅读✓ 已解决
1 回答818 阅读✓ 已解决
2 回答753 阅读
1 回答722 阅读✓ 已解决
这是一个工作示例。