3. Drawing

Open Thimble and stick this in it:

<!DOCTYPE html>
<html>
<body>
<canvas id="canvas"></canvas>
<script>
var canvas, context, mouseDown;
setup();
function setup(){
canvas = document.getElementById("canvas");
context = canvas.getContext("2d");
canvas.style.width ='100%';
canvas.width = window.innerWidth;
canvas.style.height ='100%';
canvas.height = window.innerHeight;
canvas.addEventListener("mousemove", doMouseMove, false);
}
function doMouseMove(event){
var x = event.pageX;
var y = event.pageY;
context.fillStyle = "#ff0000";
context.fillRect(x, y, 10, 10);
}
</script>
</body>
</html>

which makes this basic scribble program.

To test it, scribble on the page with your mouse, you should get red lines.

Change it, make it better.

The program below makes the rectangle on the canvas go red when you move your mouse while keeping mouse button pressed. If you only move your mouse without pressing the mouse button, it does nothing.

<!DOCTYPE html>
<html>
<body>
<canvas id="canvas"></canvas>
<script>
var canvas, context, mouseDown, mouseMove;
setup();
function setup(){
canvas = document.getElementById("canvas");
context = canvas.getContext("2d");
canvas.style.width ='100%';
canvas.width = window.innerWidth;
canvas.style.height ='100%';
canvas.height = window.innerHeight;
canvas.addEventListener("mousedown", doMouseDown, false);
canvas.addEventListener("mouseup", doMouseUp, false);
canvas.addEventListener("mousemove", doMouseMove, false);
}
function doMouseDown(event){
mouseDown = true;
drawSomething();
}
function doMouseUp(event){
mouseDown = false;
drawSomething();
}
function doMouseMove(event){
mouseMove = true;
drawSomething();
}
function drawSomething(){
if(mouseDown && mouseMove) context.fillStyle = "#ff0000";
else context.fillStyle = "#00ff00";
context.fillRect(10,10,100,100);
}
</script>
</body>
</html>

You can try it here. Change it, improve it.

If you’re bored with drawing basic rectangles without any funky borders, or even just bored of only being able to draw rectangles, check out these tutorials:

Making cool rectangles and a bit of stuff with text

Making straight lines

Making circles

I could have made a tutorial for drawing circles and stuff but I wanted you to have the experience of going round different websites, reading carefully and adapting what you learn to make something of your own – like a real programmer!