p5.js制作绘图工具

看了很多csdn上的大神做的绘图工具
p5.js制作绘图工具_第1张图片
深感惭愧

以下是我做的简易的绘图工具p5.js制作绘图工具_第2张图片
界面干净整洁

左侧图案表示
当前画笔的图形与颜色
右侧图案表示
当前画笔的大小
图案包含三种基本图形
p5.js制作绘图工具_第3张图片
下面介绍一下代码部分
首先是图形

function gui(){
  ui.fill(255,255,255)
  ui.rect(0,windowHeight-100, 100, 100)
  ui.rect(windowWidth-100,windowHeight-100, 100, 100)
  ui.fill(0,0,0)
  ui.text(dim, windowWidth-50-20,windowHeight-50-16, 100, 100)
  ui.fill(c)
  if(shape == "circle"){
    ui.ellipse(50, windowHeight - 50, 40)
  }
  else if(shape == "square" ){
    ui.rect(50 - 15, windowHeight - 50 - 15, 40, 40)
  }
  else if(shape == "triangle"){
    ui.triangle(50 - 20, windowHeight - 50 + 20, 50 + 20, windowHeight - 50 + 20, 50, windowHeight - 50 - 20)
  }
}

下面是关于一些特定的键位设置

function keyPressed() {
  if (keyCode === 27) {  //ESC  清空画布
    drw.fill(255,255,255)
    drw.rect(0,0,windowWidth,windowHeight)
    c = color(0,0,0)
    shape = "circle"
    dim = 30
    drw.fill(c)
    ui.fill(c)
  }
  else if (keyCode == 32){  //空格键  改变图形
    i++
    if(i > 2){
      i = 0
    }
    shape = shapes[i]
  }
  else if(keyCode == 38){  //上  增大画笔大小
    dim = dim + 5
    if(dim > 200)
      dim = 200
  }
  else if(keyCode == 40){  //下  减小画笔大小
    dim  = dim - 5
    if(dim < 5)
      dim = 5
  }
  else if (keyCode == 83) {  //S  保存图片
    save(drw, "painting.png")
  }
  else if (keyCode == 46){  //delete  清楚当前颜色
    c = color(255,255,255)
    ui.fill(c)
    drw.fill(c)
  }
}

接下来是关于鼠标的设置

function mouseDragged(){
    if(mouseButton == LEFT){
      if(shape == "circle"){
        drw.ellipse(mouseX,mouseY,dim)
      }
      else if(shape == "square"){
        drw.rect(mouseX-(dim/2),mouseY-(dim/2),dim,dim)
      }
      else if(shape == "triangle"){
        drw.triangle(mouseX, mouseY-(dim / 2), mouseX-(dim / 2), mouseY+(dim / 2), mouseX+(dim / 2), mouseY+ (dim / 2))
      }
    }
}

function mousePressed(){
  if(mouseButton == LEFT){
    if(shape == "circle"){
      drw.ellipse(mouseX,mouseY,dim)
    }
    else if(shape == "square"){
      drw.rect(mouseX-(dim/2),mouseY-(dim/2),dim,dim)
    }
    else if(shape == "triangle"){
      drw.triangle(mouseX, mouseY-(dim / 2), mouseX-(dim / 2), mouseY+(dim / 2), mouseX+(dim / 2), mouseY+ (dim / 2))
    }
  }
  else if(mouseButton == RIGHT){
    c = color(random(0,256),random(0,256),random(0,256))
    drw.fill(c)
    ui.fill(c)
  }
}

左键就是画画功能
右键则实现改变画笔颜色功能

以上就是我制作的画图工具
简陋但实用
以后会慢慢改进
增加多一点图案

你可能感兴趣的:(p5.js制作绘图工具)