Skip to content

Instantly share code, notes, and snippets.

@mrcoles
Created April 27, 2020 16:21
Show Gist options
  • Save mrcoles/12b34bc3bb8dd1ca3cb2212318ec04e2 to your computer and use it in GitHub Desktop.
Save mrcoles/12b34bc3bb8dd1ca3cb2212318ec04e2 to your computer and use it in GitHub Desktop.
Code to automate drawing on the canvas element on Sid’s website (using simulated mouse events).
var target = document.querySelector('canvas');
var input = document.querySelector('input.jscolor');
var body = document.body;
var rect = target.getBoundingClientRect();
var irect = input.getBoundingClientRect();
var brect = document.body.getBoundingClientRect();
var simulateMouseEvent = function simulateMouseEvent(type, point, elt, eltRect) {
elt = elt || target;
eltRect = eltRect || rect;
var event = new MouseEvent(type, {
'view': window,
'bubbles': true,
'cancelable': true,
'clientX': eltRect.left + point.x,
'clientY': eltRect.top + point.y
});
elt.dispatchEvent(event);
};
var width = target.offsetWidth;
var height = target.offsetHeight;
var drawLine = (x1, y1, x2, y2) => {
simulateMouseEvent('mousedown', {x: x1, y: y1});
simulateMouseEvent('mousemove', {x: x2, y: y2});
simulateMouseEvent('mouseup', {x: x2, y: y2});
}
var step = 3;
for (let y = 0; y < height + step; y += step) {
drawLine(0, y, width, y);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment