xxxxxxxxxx
62
// Demonstrates how to use the CPX's mouse input as a paintbrush.
// - CPX Paint 4 adds ability to change color based on keyboard string
// - CPX Paint 3 adds ability to "pick up/down" paintbrush uses mouse presses
// - CPX Paint 2 adds in clear by receiving an "UP" arrow
//
// This program is intended to be used with the CPX + MakeCode program:
// https://makecode.com/_2ws6yX6d6YXJ
//
// By Jon E. Froehlich
// https://jonfroehlich.github.io/
let brushSize = 50;
let colorFromKeyboard;
let keyboardStr = "";
let colorAlpha = 128;
function setup() {
createCanvas(400, 400);
background(220);
colorFromKeyboard = color(255, 255, 255, colorAlpha);
}
function draw() {
// background(220);
if(mouseIsPressed){
// If we're here, the mouse is pressed so let's draw a circle
fill(colorFromKeyboard);
circle(mouseX, mouseY, brushSize);
}
}
function keyPressed() {
print(key);
if (keyCode == ENTER) {
let colorAsAnInteger = parseInt(keyboardStr);
colorFromKeyboard = convertIntegerToColor(colorAsAnInteger);
keyboardStr = "";
}
else if(keyCode == DELETE){
print("DELETE key received, deleting canvas...")
background(220); // simply redraws the background on top of our painting
}
else {
// if the current key is not DELETE or ENTER, then add key to the current string
// for later parsing
keyboardStr += key;
}
}
function convertIntegerToColor(num) {
num >>>= 0;
let b = num & 0xff,
g = (num & 0xff00) >>> 8,
r = (num & 0xff0000) >>> 16,
a = ((num & 0xff000000) >>> 24) / 255;
print(num, r, g, b, a);
return color(r, g, b, colorAlpha);
}