【发布时间】:2021-02-01 13:55:41
【问题描述】:
我想实现画布作为我网站的背景,以便用户可以使用光标在网页上绘画,就像这个 codepen:https://codepen.io/cocotx/pen/PoGRdxQ?editors=1010 (这是来自http://www.dgp.toronto.edu/~clwen/test/canvas-paint-tutorial/的示例代码)
if(window.addEventListener) {
window.addEventListener('load', function () {
var canvas, context;
// Initialization sequence.
function init () {
// Find the canvas element.
canvas = document.getElementById('imageView');
if (!canvas) {
alert('Error: I cannot find the canvas element!');
return;
}
if (!canvas.getContext) {
alert('Error: no canvas.getContext!');
return;
}
// Get the 2D canvas context.
context = canvas.getContext('2d');
if (!context) {
alert('Error: failed to getContext!');
return;
}
// Attach the mousemove event handler.
canvas.addEventListener('mousemove', ev_mousemove, false);
}
// The mousemove event handler.
var started = false;
function ev_mousemove (ev) {
var x, y;
// Get the mouse position relative to the canvas element.
if (ev.layerX || ev.layerX == 0) { // Firefox
x = ev.layerX;
y = ev.layerY;
} else if (ev.offsetX || ev.offsetX == 0) { // Opera
x = ev.offsetX;
y = ev.offsetY;
}
// The event handler works like a drawing pencil which tracks the mouse
// movements. We start drawing a path made up of lines.
if (!started) {
context.beginPath();
context.moveTo(x, y);
started = true;
} else {
context.lineTo(x, y);
context.stroke();
}
}
init();
}, false); }
问题是当我滚动时光标停止绘画,直到我再次移动鼠标。关于如何在滚动时保持光标绘制的任何想法?
提前致谢!非常感谢!
【问题讨论】:
标签: javascript canvas html5-canvas