I was creating a mouse-based painter app. I wanna a brush whose color is chosen by a color picker in p5js. And I think I finished coding, but it's not working at all... and is there anybody who can help me? I wanna see where I did make mistake....! thanx, advance!
```
var brushSize;
let activeBrush = 0;
function setup() {
brushSize = 10;
createCanvas(800, 800);
colorPicker = createColorPicker('#ed225d');
colorPicker.position(600, 20);
background(220);
function draw() {
colorMode(RGB);
brushColor = colorPicker.color();
noStroke();
function keyTyped() {
if (key == '=') { //becomes bigger and smaller by 10% with [=] and [-] keys, respectively, but not working...
brushSize = brushSize brushSize*0.1;
} else if (key == '-') {
brushSize = brushSize - brushSize*0.1;
} else if (key == 'c') { //when [C] is pressed, everything on canvas gets deleted, but it's not working at all..
noStroke();//clear button
fill(220);
rectMode(CORNER);
rect(0, 0, 800, 800);
} else if (key == 's') { //when [S] is pressed, current content on canvas is saved as an image file ,, but it's not working at all..
let b = createCanvas(800, 800);
saveCanvas(b, 'myCanvas', 'jpg');
}
}
}
function mouseDragged(){
fill(colorPicker);
ellipse(mouseX, mouseY, brushSize, brushSize)}} // plus why this isn't working..?? TT
```
CodePudding user response:
It's likely that, wherever mouseX
and mouseY
are coming from in the OP code, they are wrong. Painting on drag is straight-forward. From the requirements stated in the OP, there's no need for a draw function, just add to the canvas on drag.
Here's some working code to use as a starter....
const sketch = function(p) {
p.setup = function() {
p.createCanvas(600, 600);
};
let color = 'blue';
let brushSize = 20;
p.keyPressed = function(e) {
let key = e.key;
const colors = { r: 'red', g: 'green', b: 'blue' };
if (colors[key]) {
color = colors[key];
return;
}
if (key === '=') brushSize = brushSize * 0.1;
else if (key === '-') brushSize -= brushSize * 0.1;
else if (key === 'c') p.clear();
}
p.mouseDragged = function(e) {
p.fill(color);
p.stroke(color);
p.ellipse(e.clientX, e.clientY, brushSize, brushSize / 2)
}
};
let myp5 = new p5(sketch);
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.1/p5.min.js"></script>