30天JS挑战(第八天)

67 阅读2分钟

第八天挑战(canvas笔刷)

地址:javascript30.com/

所有内容均上传至gitee,答案不唯一,仅代表本人思路

中文详解:github.com/soyaine/Jav…

该详解是Soyaine及其团队整理编撰的,是对源代码的详解强烈推荐大家观看学习!!!!!!!

本人gitee:gitee.com/thats-all-r…

效果image-20240222205249608

作者对canvas不了解,代码是按照源码仿写的,这里直接放出源码和API说明,供大家参考

官方代码

官方代码仅代表该案例原作者思路,不唯一

结构

<canvas id="draw" width="800" height="800"></canvas>

逻辑

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);
  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);

分析

仅代表本人对该代码的分析

建议直接去看Soyaine的中文详解

  • 整体思路: 监听鼠标移动事件,实时获取鼠标坐标,根据坐标绘制canvas,动态的添加颜色,如果超过阈值则置0

  • 具体实现:

    • strokeStyle:是 Canvas 2D API 描述画笔(绘制图形)颜色或者样式的属性。默认值是 #000 (black)。
    • beginPath:是 Canvas 2D API 通过清空子路径列表开始一个新路径的方法。当你想创建一个新的路径时,调用此方法。
    • moveTo:将当前窗口移动到指定的坐标位置。
    • lineTo: 是 Canvas 2D API 使用直线连接子路径的终点到 x,y 坐标的方法(并不会真正地绘制)。
    • stroke:定义了给定图形元素的外轮廓的颜色。它的默认值是 none
    • lineWidth:是 Canvas 2D API 设置线段厚度的属性(即线段的宽度)。