<div id="canvas"></div> #canvas { width: 500px; height: 500px; border: 1px solid black; }
要进行涂鸦,大家需要在JavaScript中获取这个div元素,并为其添加一个mousedown事件监听器。当鼠标点击画布时,大家将创建一个新的div元素,并将其添加到画布上。这个新的div元素代表大家要涂鸦的笔触。大家还将为这个新元素添加一个mousemove事件监听器,以便在鼠标移动时绘制出笔触。例如:
var canvas = document.getElementById('canvas'); canvas.addEventListener('mousedown', startDrawing); function startDrawing(e) { var newStroke = document.createElement('div'); newStroke.className = 'stroke'; canvas.appendChild(newStroke); newStroke.style.left = e.pageX - canvas.offsetLeft + 'px'; newStroke.style.top = e.pageY - canvas.offsetTop + 'px'; canvas.addEventListener('mousemove', draw); } function draw(e) { var strokes = document.getElementsByClassName('stroke'); var currentStroke = strokes[strokes.length - 1]; var newX = e.pageX - canvas.offsetLeft; var newY = e.pageY - canvas.offsetTop; var distance = Math.sqrt(Math.pow(newX - parseInt(currentStroke.style.left), 2) + Math.pow(newY - parseInt(currentStroke.style.top), 2)); if (distance >10) { var newSegment = document.createElement('div'); newSegment.className = 'segment'; newSegment.style.left = newX + 'px'; newSegment.style.top = newY + 'px'; currentStroke.appendChild(newSegment); } }
大家为每个笔触定义了一个CSS样式,以使其看起来像画笔划过的线条。例如:
.stroke { position: absolute; width: 0; height: 0; } .segment { position: absolute; width: 6px; height: 6px; background-color: black; border-radius: 50%; }
这些CSS样式定义了笔触(stroke)和笔画(segment)的外观。笔触使用了绝对定位(position: absolute),而笔画使用了圆形的边框半径来模拟笔触的宽度。这样,大家就可以实现一个基本的CSS涂鸦效果了。