Skip to content

Instantly share code, notes, and snippets.

@zanarmstrong
Created January 18, 2021 07:32
Show Gist options
  • Save zanarmstrong/9990a82534cfb570bae4bffbc239a748 to your computer and use it in GitHub Desktop.
Save zanarmstrong/9990a82534cfb570bae4bffbc239a748 to your computer and use it in GitHub Desktop.
draw your data
var img = new Image();
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
let coords = [];
img.onload = function() {
ctx.drawImage(img, 0, 0);
};
function clearPixel(x,y) {
var pixel = ctx.getImageData(x, y, 1, 1);
pixel.data[3] = 0;
ctx.putImageData(pixel,x,y);
}
function pick(event) {
var x = event.layerX;
var y = event.layerY;
if(coords[x]){
clearPixel(x,coords[x])
}
var pixel = ctx.getImageData(x, y, 1, 1);
coords[x] = y;
pixel.data[0] = 0;
pixel.data[1] = 0;
pixel.data[2] = 255;
pixel.data[3] = 255;
ctx.putImageData(pixel,x,y);
}
canvas.addEventListener('mousemove', function(event) {
pick(event);
});
document.getElementById('clear').addEventListener('click', function(){
coords = [];
ctx.clearRect(0, 0, canvas.width, canvas.height);
document.getElementById("output").innerHTML = ""
});
document.getElementById('showvalues').addEventListener('click', function(){
let valueString = "";
let htmlstring = "<p>x,y</p>"
coords.forEach((d,i)=>{
valueString = valueString + i + "," + (canvas.height - d) + "\n";
htmlstring = htmlstring + "<p>" + i + "," + (canvas.height - d) + "</p>"
});
console.log(valueString);
document.getElementById("output").innerHTML = htmlstring;
});
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Draw a curve, get coords</title>
<style>
#canvas {
border: solid 5px;
margin: 20px;
}
.clickable {
cursor: pointer
}
p {
margin: 0px 0px 0px 20px
}
</style>
</head>
<body>
<h1>Draw a function</h1>
<div>
<p>Note: only one value per x coord will be allowed.</p>
<canvas id="canvas" width="500" height="300"></canvas>
<p id="clear" class="clickable">*click to clear*</p>
<p id="showvalues" class="clickable">*click to paste coordinates*</p>
<div id="output"></div>
</div>
<script src="drawacurve.js"></script>
</body>
</html
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment