Draggable

Select and drag elements on a canvas.

Source Code for this Sketch

// grid draws a grid of desired spacing and color, with
// optional numbering
function grid(spacing, color, numbering) {
	if (typeof numbering === "undefined") {
		numbering = false
	}

	fill(color)
	stroke(color)
	strokeWeight(1)
	textSize(9)

	if (numbering) {
		text("0", 5, 10)
	}

	for (let i = spacing; i < width; i += spacing) {
		if (numbering) {
			text(i, i + 5, 10)
		}
		line(i, 0, i, height);
	}
	for (let i = spacing; i < height; i += spacing) {
		if (numbering) {
			text(i, 5, i + 10)
		}
		line(0, i, width, i);
	}
}

// labelPosition draws a label at x,y indicating the selected x,y
// coordinates. if showLine is true it also draws a short
// connecting line between the text and the coordinate label,
// with optional color
function labelPosition(x, y, showLine, c) {
	push()
	colorMode(HSL)
	c = c ? c : color(220, 100, 50)

	// Make sure the label appears near the point, but not
	// off the edge of the canvas, or below the mouse cursor
	let showX = x + 15
	let showY = y + 10
	let anchorX = x + 12
	let anchorY = y + 8
	if (x > width * .8) {
		showX = x - 50
		anchorX = x - 6
	}
	if (y > height * .9) {
		showY = y - 10
		anchorY = y + -12
	}

	// Draw the label
	strokeWeight(0)
	fill(c)
	text("(" + round(x) + ", " + round(y) + ")", showX, showY)

	if (showLine) {
		strokeWeight(1)
		stroke(c)
		line(x, y, anchorX, anchorY)
	}
	pop()
}



let dh = {}

function setup() {
	createCanvas(400, 400, P2D, canvas)
	colorMode(HSL)
	angleMode(DEGREES)

	dh.cookies = new DragHandle(50, 50, color(0, 0, 100))
	dh.cookie0 = new DragHandle(50, 60, color(0, 100, 50))
	dh.cookie1 = new DragHandle(50, 70, color(40, 100, 50))
	dh.cookie2 = new DragHandle(50, 80, color(80, 100, 50))
	dh.cookie3 = new DragHandle(50, 90, color(120, 100, 50))
	dh.cookie4 = new DragHandle(50, 100, color(160, 100, 50))
	dh.cookie5 = new DragHandle(50, 110, color(200, 100, 50))
	dh.cookie6 = new DragHandle(50, 120, color(240, 100, 50))
	dh.cookie7 = new DragHandle(50, 130, color(280, 100, 50))
	dh.cookie8 = new DragHandle(50, 140, color(320, 100, 50))
	dh.cookie9 = new DragHandle(50, 150, color(320, 30, 50))
	dh.cooki10 = new DragHandle(50, 160)

}

function draw() {
	background(45, 40, 85)

	grid(50, color(45, 30, 65), true)

	for (let i in dh) {
		if (dh.hasOwnProperty(i)) {
			dh[i].draw()
		}
	}
}

You may use all or part of the p5 code seen on this page for your own creations, without restriction. Attribution is appreciated but not required.

This sketch also includes the following sources: p5common.js . Sources are available under their respective licenses.

See all p5.js sketches