承接上文,这是第8个案例,要实现的效果是按住鼠标不放,进行拖动时可以在画布上画出不同粗细不同颜色的曲线。
附上项目链接: https://github.com/wesbos/JavaScript30
主要思路:鼠标按下时,记录当前x,y坐标,作为起点,鼠标移动时开始画线。鼠标左键抬起或移出画布时停止绘画。没什么讲的,有个值得注意的点,hsl这个表现颜色,我之前不知道的。附上源码:
<script>const canvas = document.querySelector('#draw');const ctx = canvas.getContext('2d');canvas.width = window.innerWidth;canvas.height = window.innerHeight;ctx.strokeStyle = '#BADA55';ctx.lineJoin = 'round';ctx.lineCap = 'round';ctx.lineWidth = 100;// ctx.globalCompositeOperation = 'multiply'; let isDrawing = false;let lastX = 0;let lastY = 0;let hue = 0;let direction = true;function draw(e) {if (!isDrawing) return; // stop the fn from running when they are not moused down console.log(e); // HSL(H,S,L),css3颜色值表示方式, // H:Hue(色调)。0(或360)表示红色,120表示绿色,240表示蓝色,也可取其他数值来指定颜色。取值为:0 - 360 // S:Saturation(饱和度)。取值为:0.0% - 100.0% // L:Lightness(亮度)。取值为:0.0% - 100.0%ctx.strokeStyle = `hsl(${hue}, 100%, 50%)`;ctx.beginPath();// start from ctx.moveTo(lastX, lastY);// go to ctx.lineTo(e.offsetX, e.offsetY);ctx.stroke();[lastX, lastY] = [e.offsetX, e.offsetY];hue++;if (hue >= 360) {hue = 0;}if (ctx.lineWidth >= 100 || ctx.lineWidth <= 1) {direction = !direction;}if (direction) {ctx.lineWidth++;} else {ctx.lineWidth--;}}canvas.addEventListener('mousedown', (e) => {isDrawing = true;[lastX, lastY] = [e.offsetX, e.offsetY];});canvas.addEventListener('mousemove', draw);canvas.addEventListener('mouseup', () => isDrawing = false);canvas.addEventListener('mouseout', () => isDrawing = false);</script>